Creating containers c++ [closed] - c++

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm wondering if creating my own container is very useful ? There are a few containers already implemented in c++ but what are the advantages of creating my own container ?
More information : I am a beginner.
Edit : can someone give me an example of what a Standard Library container can't do ?

If your intent is to learn about the containers and C++, by all means, go ahead and try to implement them. If you just want to use a container and it exists in the standard library, boost, or some other reputable library you have in your project, just use the library version. It's likely to be well tested and optimized. Other programmers are also likely to be more familiar with that container than something you roll out yourself.
A rule of thumb is, reuse code, unless you can do better and can justify the associated cost.

If you want to learn how to program, or understand how containers work, or everything related to them, then your own implementation of containers is a good practice.
However, large companies often also use their own containers, as they may consider standard containers and algorithms not optimal for their own tasks.

There are several non-standard containers in Boost, like the ones in Boost.Container or Boost Graph Library, so there's certainly some ground the STL doesn't cover.
Generally speaking, start with std::vector and check the other STL containers if it doesn't meet your requirements.

C++ Standard Library is a general purpose library for C++ programming language. In is designed to be well enough for most tasks you may encounter in your job. But sometimes it can turn out that some container from Standard Library does not fit your needs. This is the case when you can implement your own version of some container because Standard Library can't satisfy absolutely every need that can arise during your work.

I'm wondering if creating my own container is very useful ?
It could be.
My understanding of containers is template-s in C++ code
A simple example are matrixes. You may want to develop your own template<unsigned Height,unsigned Width,typeclass ElementType> class Matrix, and you would certainly call that a container. Remember that matrices of polynomial makes sense in mathematics.
A typical example is numerical scientific computations, related to representing huge mathematical symmetrical or triangular or diagonal or sparse (etc...) matrixes on various kind of numbers (float-s, but also bignums). Think of finite element methods computation.
The opencv library is an open source C++ library on computer vision which uses template-s. Download its source code and study it.
Another example is some heavy C++ software taking advantage of OpenCL (when that is available).
Or representing efficiently in memory a mathematical permutation between integers less than some given N. You may want to represent that as two std::vectors (one for the direct, another for the inverse mapping) inside your own template.
Some generic parsing libraries in C++ are heavily using templates.
The Qt graphical toolkit is coded in C++, is open source, and has template-s.
The tensorflow machine learning library has open source C++ code with template-s.
The Wt web toolkit is coded in C++, is open source, and uses template-s. You can download and study its source code. My opinion is that it has specialized containers.
The GCC compiler is coded mostly in C++, is free software, and uses template-s. You can download and study its source code. My opinion is that it has specialized containers.
A third example is garbage collection support. The RefPerSys project has templates...
A fourth example could be related to storing your C++ container in a database (like PostgreSQL)
Don't forget another approach: generating C++ code (like SWIG or ANTLR does) from some higher-level description. And be aware of the rule of five.
See also Autosar MISRA C++ coding guidelines.

Related

Differences between Wrapper and Library [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I am curious to know the differences between a Wrapper and a Library.
From what I have been able to find online I can't really see any major difference between the two. I often came across "Wrapper Library" or "Library Wrapper" and it makes it seem as if they are basically one in the same.
However, my assumption is that a Library is a collection of finely tuned functions that provide a means to accomplish a task that isn't part of the core functionality in the language.
And a Wrapper is a facade that makes it easier and quicker to set up certain functionality within your program so that you have less typing to do.
These two descriptions just make it seem like it's the same thing with different wording to me though.. so I come to you Stackoverflow,
What are your opinions and professional points of view on Wrappers/Libraries?
Sidenote/Background:
This question stems from my C++ Design Patterns Class I finished a month ago:
In my C++ Software Design Patterns class we had to create a Socket Library that took the WinSock Library and created a Thin(Or Thick, our choice) Wrapper over it. We then had to create two applications that used our library so that we didn't have to repeat the basic set up and tedious coding of the WinSock Library. I ended up with 100% on the project but wish to know more about the actual differences or similarities because I want to expand on this project in my personal time.
In general, I personally think of it like this:
A library is typically an actual concrete implementation of some functionality.
A wrapper is mostly just a layer of abstraction around existing functionality. It is only intended to offer a better, cleaner interface (or at least one feels more native to the language or technology it targets) to something that already exists.
Now obviously there are times when the distinction between the two is crystal clear and times when the line is blurred, so some subjectivity may be inevitable in the latter scenarios. In other words, what you consider an implementation and what you consider simply an abstraction can be ambiguous occasionally.
For instance, a wrapper can have argument checking functionality or better state bookkeeping that the underlying system did not have. If this is mostly to serve the correctness of the abstraction, then it this still leans on the side of the wrapper. If some genuinely new functionality is added, it starts becoming a library and could be called a wrapper-library.
On the other hand, a full-fledged library may not be a wrapper at all, in the sense that it may leverage an underlying system to offer some functionality, but without exposing any considerable part of that underlying system in any clean interface (other than the specific functionality it adds). This would be called a library, but most probably it wouldn't be called a wrapper.
(I should clarify that what I said is how I think of the matter in general, not specifically in regard to C++. If the C++ world has less ambiguous definitions of these terms, please do correct me.)
Library is an generic implementation of any sort of functionality. Wrapper is a specific implementation intended to provide abstraction to existing library.

LEDA graph v/s Boost Graph library [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I want efficiency and I am willing to write code by myself if efficiency (=0.9*speed + 0.1*others) is high. If I were to choose between LEDA graph or Boost graph, which one should I choose?
My algorithms are time-consuming (some are even non-polynomial in time) which works on large graphs.
Boost is generally a good library but I would not suggest Boost graph for a number of reasons.
The BGL documentation is execrable, with no easy to follow user guide. I have found that trying to define graphs with properties that are relevant to my own problems is very difficult.
You frequently end up with huge compiler errors that show templates within templates within templates ... nigh on impossible to see what is going on.
The only solution I found was to start with a trivial example that comes with Boost Graph, and adapt it until it does what I want.
I know of many bright and capable people that have ditched Boost Graph because of these reasons. Sad since there are very efficient algorithms underneath it all. For me BGL is the textbook example of template overuse. Boost Graph is a great idea that fails by missing the point entirely: code is worthless if it can't be read, maintained, extended, or debugged.
There are alternatives to LEDA/Boost implementation. You could do worse than to investigate this similar-sounding posting:
https://stackoverflow.com/questions/510758/can-you-suggest-a-good-book-on-graphs-and-graph-algorithms (link is no longer valid)
The Boost is continually refactored so parts of it get moved into the standard, after which vendor's continue to optimize it for the target systems they support. On rare usage scenarios, using inheritance the developer may tweak some part for specific case.
If the work is confined to C++, then as the parts of Boost are aiming to get integrated into the standard, it does have these advantages. There maybe specific reason to use proprietary LEDA, such as being guaranteed error free by testing, then as the decision maker only you have to observe such criteria.
Boost graph algorithms can be made to work on LEDA and even stanford graph base graphs, but not the other way around.
http://www.boost.org/doc/libs/1_46_1/libs/graph/doc/leda_conversion.html
I would suggest to use boost graph, it is the state of the art.
mike

Should programmers use STL or write their own code? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Opinion-based Update the question so it can be answered with facts and citations by editing this post.
I don't know much about C++ data structures but I am wondering do you (programmers) use STL or write your own code? After all STL is designed for doing tasks like searching, replacing and much more through a list of data.
Someone really don't need to learn much about the linked list, binary search and many more because I could use STL. What would you suggest?
You should use STL, because it is well tested and optimized.
That doesn't mean you shouldn't know how to write these data structures yourself. With that ability under your belt, you will be able to choose the best STL data structure for your application.
While the Standard Template Library is convenient when it comes to performing tasks as you mentioned like Searching, Replacing, using Linked Lists, it should not replace the knowledge of what is going on inside of the Library.
You mentioned not needing to learn about linked lists, binary searches and "many more", however you should have at least a working knowledge of how these Data Structures and procedures work as it will make using them (and knowing when to use them) much more effective.
Basically - you don't have to reinvent the wheel, but at least know what makes the wheels effectively turn.
Use STL and standard libraries in general when you can. First it is probably way better tested than your own code, and second it helps keep your code portable. The only time you should rewrite any of this functionality is for learning purposes. It may be educational to write your own associative map or linked list, but for production code, stick with well tested and standard compliant code.
A working knowledge of the underlying data structures, methods and applications of the tools provided by the STL will make you a much better programmer. Knowing when to use what container type, or which algorithm is as important as a proper implementation. Sometimes, the easiest way to understand some of the more complex concepts is to implement them yourself in the context of a data structures and algorithms class.
That said, the code in the STL has been written by experts and refined over time into a standard library that is used my millions of people world wide. In practicality, there is almost never a reason to "roll your own" except for extreme cases where performance (or size) matter to a point that is critical for your exact application.
I hesitate to write, since I haven't written C++ in 5 years. But a couple of things came to mind that haven't been discussed yet.
If the implementation is a bad fit for what you need, don't use it if you can write and test your own easier than using the library. I recently ran into this in Java, where I needed a fast bitset. Details:: There are two relevant classes in the JVM (BitSet and BigInteger). BitSet doesn't support initialization other than by setting one bit at a time; BigInteger has an irrelevant signum that confused things, and is immutable, which is costly in my case. I ended up writing my own, with tests, in a few hours. It fits better, is faster, and I can do whatever I want to it.
The other reason to write your own is if you don't understand the specification of the library implementation relative to your requirements, can't easily test it or read it to figure out what it does, and can easily roll your own. This is/was a particular problem with STL implementations that are (or at least used to be) shipped with terse, inadequate, cryptic documentation and commentless, opaque source code that rolls over your head like a huge rogue wave.
Just to add my answer (from comment above):
Yes you should think about implementing e.g. a sequence, a linked list, using your own code.
This is what they teach on Comp Sci courses and it is not without good reason. But, if you're looking to work quickly then just use STL.
I just think people should understand how the tools really work.
I use the C/C++ Standard library and STL because it is a really big time saver and I don't see the need to reinvent the wheel. I also use boost where I can.
It is still a good learning exercise to write your own container class and algorithms.
Use STL unless you have a compelling reason, e.g. speed or correctness, not to. Definitely know how to write basic data structures on your own.
In general you should use STL or Boost containers because of their effectiveness and reliability. Still you need to have a corresponding world view on existing containers. You should know its con and pros. Studying of the container internal structure and working principles allows you to reach better understanding.
STL is well tested and reliable but it is not the fastest solution. Some of the containers allocate a lot of small memory blocks rather than one big block. If you really have a speed problem then you may consider making your own fixed-size list. But for many purposes STL is the standard solution.
Very smart people wrote the STL. Then more very smart people have used it, tested it, and refined it. You think you are going to do better? Rarely. It is a great tool; you should use it whenever possible!
Write low-level stuff yourself when learning/playing, but at work use code that was written and refined by experts over years, and has/is being tested by thousands of engineers in thousands of different conditions.
In other words, use your code only if your code can beat the other codes!

What should I learn first before heading to C++? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm learning C, but after that or in the meanwhile, what should I learn first and subsequently before getting into C++ ? Compilers, Data Structures, UML or Design Patterns ?(also when start to learn Win32 API ?) I'm not in a hurry at all, so I can grasp the requirements from the deepest beginning. I just don't want to get lost for being cursory and negligent.
In addition to this, which subjects on mathematics has most impact on coding very well ? Linear Algebra, Discrete Mathematics, Calculus ?
I'll be thankful if someone guides me through this journey. There are many questions I would like to know the answers. Thanks.
First you should learn that C++ is not a superior language. C has its uses as more than a stepping stone into C++. C, and "C-style" C++ are used because they:
Generate smaller binaries
Use less memory
Compile faster
Do not require OS-support
Are simpler, and easier to implement
Data structures are by far the most useful of the listed to learn, followed by algorithms. If you intend to go into C++, it's also useful (mandatory?) to have good design skills.
You should not necessarily learn Win32 at all. Consider learning the POSIX APIs, GTK+ and Boost, as they're more portable, and work on platforms other than Windows.
The best decision you can make is to learn C thoroughly as a separate skill on a Unix platform, before crutching yourself by not being able to see the difference between C and C++.
Of the listed Mathematics disciplines, I've only used discrete mathematics. Linear algebra is also useful, but by far and away the best discipline for programming is set and number theory.
Enjoy your time in C, don't become dependent on Windows/Visual Studio, and don't rush into C++.
Update0
Almost forgot! You absolutely must use a decent C compiler. A central reason to C++'s wide use in enterprise, and the bad reputation C has among Windows developers is Visual Studio. Visual Studio is easily the best C++ IDE, however it's also the worst C compiler I know of. Be sure to use a C compiler with C99 support, such as GCC, mingw or Clang. My first experience with C was using LCC, which was very easy to use on Windows, but I haven't used it since moving to Linux, so I can't comment on its C99 status.
Compilers, Data Structures, UML or Design Patterns ?
Data Structures and Algorithms.
In addition to this, which subjects on mathematics has most impact on coding very well ? Linear Algebra, Discrete Mathematics, Calculus ?
Discrete Mathematics and Number Theory.
You should learn to program in a well structured language first: Ocaml is recommended, Haskell is also good but a bit harder to get a working compiler and harder to learn because it is purely functional.
Mathematics is of little use in programming (the math that is useful is too hard, namely category theory). However some basic type theory is useful.
You can't learn good programming in languages like C, the important stuff is too deeply buried in housekeeping tasks and historical stupidities.

To STL or !STL, that is the question [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Unquestionably, I would choose to use the STL for most C++ programming projects. The question was presented to me recently however, "Are there any cases where you wouldn't use the STL?"...
The more I thought about it, the more I realized that perhaps there SHOULD be cases where I choose not to use the STL... For example, a really large, long term project whose codebase is expected to last years... Perhaps a custom container solution that precisely fits the projects needs is worth the initial overhead? What do you think, are there any cases where you would choose NOT to STL?
The main reasons not to use STL are that:
Your C++ implementation is old and has horrible template support.
You can't use dynamic memory allocation.
Both are very uncommon requirements in practice.
For a longterm project rolling your own containers that overlap in functionality with the STL is just going to increase maintenance and development costs.
Projects with strict memory requirements such as for embedded systems may not be suited for the STL, as it can be difficult to control and manage what's taken from and returned to the heap. As Evan mentioned, writing proper allocators can help with this, but if you're counting every byte used or concerned with memory fragmentation, it may be wiser to hand-roll a solution that's tailored for your specific problem, as the STL has been optimized for the most general usage.
You may also choose not to use STL for a particular case because more applicable containers exist that are not in the current standard, such as boost::array or boost::unordered_map.
There are just so many advantages to using the stl. For a long term project the benefits outweigh the costs.
New programmers being able to understand the containers from day one giving them more time to learn the other code in the project. (assuming they already know STL like any competent C++ programmer would)
Fixing bugs in containers sucks and wastes time that could be spent enhancing the business logic.
Most likely you're not going to write them as well as the STL is implemented anyways.
That being said, the STL containers don't deal with concurrency at all. So in an environment where you need concurrency I would use other containers like the Intel TBB concurrent containers. These are far more advanced using fine grained locking such that different threads can be modifying the container concurrently and you don't have to serialize access to the container.
Usually, I find that the best bet is to use the STL with custom allocators instead of replacing STL containers with hand rolled ones. The nice thing about the STL is you pay only for what you use.
I think it's a typical build vs buy scenario. However, I think that in this case I would almost always 'buy', and use STL - or a better solution (something from Boost perhaps), before rolling my own. You should be focusing most of your effort on what your application does, not the building blocks it uses.
I don't really think so. In making my own containers, I would even try to make those compatible with the STL because the power of the generic algorithms is too great to give up. The STL should at least be nominally used, even if all you do is write your own container and specialize every algorithm for it. That way, every sorting algorithm can be invoked sort(c.begin(), c.end()). If you specialize sort to have the same effect, even if it works differently.
Coding for Symbian.
STLPort does support Symbian 9, so the case against using STL is weaker than it used to be ("it's not available" is a pretty convincing case), but STL is still alien to all the Symbian libraries, so may be more trouble than just doing things the Symbian way.
Of course it might be argued on these grounds that coding for Symbian is not "a C++ programming project".
Most of the projects I have worked on had a codebase way older than any really usable version of STL - therefore we chose not to introduce it now.
Introduction:
STL is a great library, and useful in many cases, but it definitively don't solve all the situations. Answering STL or !STL is like answering "Does STL meet your need or does it not?"
Pros of STL
In most situations, STL has a container that fit for a given solution.
It is well documented
It is well known ( Programmers usually already know it, getting into a project is shorter)
It is tested and stable.
It is crossplatform
It is included with every compiler (does not add a 3rd library dependency)
STL is already implemented and ready
STL is shiny, ...
Contras of STL
It does not mater that you need a simple Graph, Red-Black Tree, or a very complex database of elements with an AI managing concurrent access through a quantum computer. The fact is, STL do not, and will never solve everything.
Following aspects are only a few examples, but they basically are consequence of this fact: STL is a real library with limits.
Exceptions: STL relay on exceptions, so if for any reason you cannot accept exceptions (e.g. safety critical), you cannot use STL. Right! exceptions may be disabled, but that does not solve the design of the STL relaying on them and will eventually carry a crash.
Need of specific (not yet included) data structure: graph, tree, etc.
Special constraints of complexity: You could discover that STL general purpose container is not the most optimal for your bottleneck code.
Concurrency considerations: Either you need concurrency and STL do not provide what you need (e.g. reader-writer lock cannot(easily) be used because of the bi-directional [] operator). Either you could design a container taking benefit of multi-threading for a much faster access/searching/inserting/whatever.
STL need to fit your needs, but the revers is also true: You need to fulfill the needs of STL. Don't try to use std::vector in a embedded micro-controller with 1K of unmanaged RAM.
Compatibility with other libraries: It may be that for historical reasons, the libraries you use do not accept STL (e.g. QtWidgets make intensive use of it own QList). Converting containers in both directions might be not the best solution.
Implementing your own container
After reading that, you could think: "Well, I am sure I may do something better for my specific case than STL does." WAIT!
Implementing your container correctly become very quickly a huge task: it is not only about implementing something working, you might have to:
Document it deeply, including limitations, algorithm complexity,etc.
Expect bugs, and solving them
Incoming additional needs: you know, this function missing, this conversion between types, etc.
After a while, you could want to refactor, and change all the dependencies (too late?)
....
Code used that deep in the code like a container is definitively something that take time to implement, and should be though carefully.
Using 3rd party library
Not STL does not necessarily mean custom. There are plenty of good libraries in the net, some even with permissive open-source license.
Adding or not an additional 3rd party library is another topic, but it worth to be considered.
One situation where this might occur is when you are already using an external library that already provides the abilities you need from the STL. For instance, my company develops an application in space-limited areas, and already uses Qt for the windowing toolkit. Since Qt provides STL-like container classes, we use those instead of adding the STL to our project.
I have found problems in using STL in multi-threaded code. Even if you do not share STL objects across threads, many implementations use non-thread safe constructs (like ++ for reference counting instead of an interlocked increment style, or having non-thread-safe allocators).
In each of these cases, I still opted to use STL and fix the problems (there are enough hooks to get what you want).
Even if you opt to make your own collections, it would be a good idea to follow STL style for iterators so that you can use algorithms and other STL functions that operate only on iterators.
The main issue I've seen is having to integrate with legacy code that relies on non-throwing operator new.
I started programming C back in about 1984 or so and have never used the STL. Over the years I have rolled my own function librarys and they have evolved and grown when the STL was not stable yet and or lacked cross platform support. My common library has grown to include code by others ( mostly things like libjpeg, libpng, ffmpeg, mysql ) and a few others and I would rather keep the amount of external code in it to a minimum. I'm sure now the STL is great but frankly I'm happy with the items in my toolbox and see no need at this point to load it up with more tools. But I certainly see the great leaps and bounds that new programmers can make by using the STL without having to code all that from scratch.
Standard C++ perversely allows implementations of some iterator operations to throw exceptions. That possibility can be problematic in some cases. You might therefore implement your own simple container that is guaranteed not to throw exceptions for critical operations.
Since almost everybody who answered before me seemed so keen on STL containers, I thought it would be useful to compile a list of good reasons not to use them, from actual problems I have encountered myself.
These can be reasonably grouped into three broad categories:
1) Poor efficiency
STL containers typically run slower AND use too much memory for the job. The reason for this can be partly blamed on too generic implementations of the underlying data structures and algorithms, with additional performance costs deriving from all the extra design constrains required by the tons of API requisites that are irrelevant to the task at hand.
Reckless memory use and poor performance go hand in hand, because memory is addressed on the cache by the CPU in lines of 64 bytes, and if you don't use locality of reference to your advantage, you waste cycles AND precious Kb of cache memory.
For instance, std::list requires 24 bytes per element rather than the optimal 4.
https://lemire.me/blog/2016/09/15/the-memory-usage-of-stl-containers-can-be-surprising/
This is because it is implemented by packing two 64-bit pointers, 1 int and 4 bytes of memory padding, rather than doing anything as basic as allocating small amounts of contiguous memory and separately tracking which elements are in use, or using the pointer xor technique to store both iteration directions in one pointer.
https://en.wikipedia.org/wiki/XOR_linked_list
Depending on your program needs, these inefficiencies can and do add up to large performance hits.
2) Limitations / creeping standards
Of course, sometimes the problem is that you need some perfectly common function or slightly different container class that is just not implemented in STL, such as decrease_min() in a priority queue.
A common practice is to then to wrap the container in a class and implement the missing functionality yourself with extra state external to the container and/or multiple calls to container methods, which may emulate the desired behavior, but with a performance much lower and O() complexity higher than a real implementation of the data structure, since there's no way of extending the inner workings of the container. Alternatively you end up mashing up two or more different containers together because you simultaneously need two or more things that are fundamentally incompatible in any one given STL container, such as a minmax heap, a trie (since you need to be able to use agnostic pointers), etc.
These solutions may be ugly and add on top of the other inefficiencies, and yet the way the language is evolving the tendency is to only add new STL methods to match C++'s feature creep and ignore any of the missing core functionality.
3) Concurrency/parallelism
STL containers are not thread-safe, much less concurrent. In the present age of 16-thread consumer CPUs, it's surprising the go-to default container implementation for a modern language still requires you to write mutexes around every memory access like it's 1996. This is, for any non-trivial parallel program, kind of a big deal, because having memory barriers forces threads to serialize their execution, and if these happen with the same frequency as an STL call, you can kiss your parallel performance goodbye.
In short, STL is good as long as you don't care about performance, memory usage, functionality or parallelism.
STL is of course still perfectly fine for the many times you are not bound by any of these concerns and other priorities like readability, portability, maintainability or coding speed take precedence.