C++ Container selection/choices - c++

There is plenty of discussion on StackOverflow and other sites on what type of C++ container to use, with the not so shocking conclusion "it depends on your needs".
Currently i'm using std::list on my interfaces, however i have no direct requirement on lists as opposed to vectors or deques; and in there lies my question.
I can't say what my requirements will be down the line. Todays its a list, tomorrow... who knows?
I've been toying with the idea of creating a wrapper class 'Collection' which does nothing more than expose the STL containers interface allowing me to alter the internals without breaking my interfaces if the need arises.
Is this worth the hassle?
Should i just suck it up and make a decision on my current needs?
Any opinions?
Cheers,
Ben
EDIT:
Thread safety is important.
The recompilation of code that consumes the interface is unacceptable.

You should write such class if only you are going to make an option in your program to use different container type or create some kind of run-time optimization but in general you should know what the container is used for and so you know how it's used and that leads to what your needs are.
Don't make a class that you use just because you don't understand different containers because it's a waste of resources. In such case you should learn more about a few main container types, such as list, vector, queue, probably map, and use whenever they are needed. The only reason why there are so many of them is that different situations require different containers to make programming easier and code more efficient. For example lists are good if you put and remove a lot while vector is faster if you do more of reading. Queues are good when there is a need to do things in exact order (priority_queue is the same, by the way, except you can use a specific order), maps are good for hashing current state or something like that.

You should write your code generically. But instead of defining a generic Container, use the STL way of decoupling algorithms from containers (iterators). Since you want to link dynamically, read this article, and you may find some things in boost (any_range...).

If you need a single container and want to change its type quickly, use a typedef as recommended by #icabod.
If you're writing algorithms that should work with different containers selected at compile-time, then implement them as template code on containers, or, if possible, iterators.
Only if you need to select a container type at run-time you should implement a polymorphic Container or Collection class + subclasses.

Related

Why do we need stacks when we already have vectors which are even more powerful?

In C++ STL, Stacks are implemented using container adaptors which rewrite the interface of the Vector class. However, why is it necessary to do the interface rewriting and design a Stack class when there is already the Vector class available? Is it due to cost efficiency i.e. maintaining a stack uses less resources while it could do all necessary jobs?
Why do we need for loops and while loops when we already have goto which is even more powerful? You should adhere to the principle of parsimony - use the least powerful tool that is powerful enough to achieve the desired objective.
If what you need is a stack, take a dependency on the standard library class that provides that functionality, not a more powerful one. It also communicates better to a person reading your code, what you are going to do.
The idea behind the container adaptors was to enforce particular abstract data types on an otherwise open-ended container type. If you have a std::vector, it's possible to inadvertently insert/erase/access elements in the middle; but if you have a std::stack you know that won't happen. It's similar to const: You tell the compiler what restrictions to apply, so that it tells you when you accidentally violate them.
IME, people don't really use stack and queue very often. priority_queue is a little more useful. But in each case, one tends to find the odd special case where you need to break the rules a little, and that means foregoing the overly-principled container adaptors.

Design rationale behind STL

I was looking at a few sources for STL implementations (SGI, STLport, libc++) and saw a few design patterns that seemd common to all or most implementations, but I could find no reason for. I assume there must be a good reson, and want to know what it is:
Many classes, including vector and list_iterator among others, were implemented as 2 classes, e.g. list_iterator_base with part of the functionality, and then list_iterator which inherits list_iterator_base with the rest of the interface. What is the point? It seems it could be done jut as easily in one class.
The iterators seem to not make use of the iterator class. Is there some performance penalty to using it?
Those are 2 questions I found in just a quick skim. If anyone knows of a good resource explaining the implementation rationale of a STL implementation, I will be happy to hear of it.
The answers are fairly straight forward:
STL is all about generic programming. The key idea is not to have duplicate code. The immediate goal is to not have duplicate source code but as it turns out it also makes sense to not duplicate binary code. Thus, it is quite common that STL components factor commonly used parts out and use them. The links for a list class or the type independent attributes of a vector are just two examples. For vectors there are even multiple layers: some parts are entirely independent of the type (e.g., the size), others only need the type itself (e.g., all the accessors, the iterators, etc.), and some parts need to know how to deal with resource allocation (e.g., insertion and destruction needs to know about the allocator being used).
It turns out that std::iterator<...> doesn't really work: The types defined in base classes depending on template parameters are not directly accessible in class template deriving from such a base. That is, the types need to be qualified with the base class and need to be marked as types using typename. To make matters worse, users could in theory allocate objects of the derived class and release them through a pointer to std::iterator<...> (yes, that would be a silly thing to do). That is, there is no benefit but a potential drawback, i.e., it is best avoided.
That said, I'm not aware of any good resource covering the techniques of implementing generic libraries. Most of the details applied in STL implementations were independently invented by multiple people but the literature on Generic Programming is still relatively scarce. I don't think that any of the papers describing STL actually discuss implementation techniques: They normally concentrate on design details. Given that only very few people seem to understand what STL is about, it isn't a big surprise that authors tend to concentrate on describing what STL is rather than how to implement it.

Why isn't there a common base for the standard library containers?

Just out of interest...
If I were to design a library of containers, I would surely derive them from a common base class, which would have (maybe abstract) declarations of methods like size() and insert() .
Is there a strong reason for the standard library containers not to be implemented like that?
In C++, inheritance is used for run-time polymorphy (read: run-time interface reuse). It comes with the overhead of a redirection via the vtable at runtime.
In order to have the same interface for multiple container classes (so that the API is predictable and algorithms can make assumptions), there's no need for inheritance. Just give them the same methods and you're done. The containers (and algorithms) in C++ are implemented as templates, which means that you get compile-time polymorphy.
This avoids any run-time overhead, and it is in line with the C++ mantra "Only pay for what you need".
Java collections (which you probably have in mind) have a bunch of common methods implemented in AbstractCollection, that sit on top of the size() and iterator() methods implemented in the concrete class. Then IIRC there are more such methods in AbstractList and so on. Some subclasses override most of those methods, a few can get away with implementing little more than the required abstract methods. Some of the methods genuinely are implemented in common across most or all collections sharing an interface. For example the one that gives you a non-modifiable view is a total PITA to write, in my bitter experience.
C++ containers have a few member functions in common to all containers, pretty much none of which could be implemented the same way for all containers[*]. Where there are common algorithms that can be performed using an iterator (like find), they are free functions in <algorithm>, far from anywhere that inheritance gets a look-in.
There are also member functions common to all sequences, to all associative arrays, etc. But again for each of those concepts there isn't much in common between the implementations for different concrete data structures.
So ultimately in comes down to a question of design philosophy. Both Java and C++ have some code reuse in respect of containers. In C++ this code reuse comes through function templates in <algorithm>. In Java some of it comes through inheritance.
The main practical difference probably is that in Java your function can accept a java.util.Collection without knowing what kind of collection it is. In C++ a function template can accept any container, but a non-template function cannot. This affects the coding style of users, and is also informed by it - Java programmers are more likely to reach for runtime polymorphism than C++ programmers.
From an implementer's point of view, if you're writing the library of C++ containers then there is nothing to stop you from sharing private base classes between different containers in std, if you feel that will help reuse code.
[*] Now that size() is guaranteed O(1) in C++11, empty() could probably be implemented in common. In C++03 size() merely "should" be O(1), and there were implementations of std::list that took advantage of this to implement one of the versions of splice in O(1) instead of the O(n) it would take to update the size.
There is no good reason to introduce such base class. Who would benefit from it? Where would it be useful?
Algorithms that require a 'generic' interface use iterators. There is no common way of inserting elements to different containers. In fact, you cannot even insert elements to some containers.
It would make sense if you could write code that is independent of the container you are using. But that's not the case. I recommend you to read this chapter "Item 2: Beware the illusion of container-independent code" of the book Effective STL.
From another viewpoint: right now, if you use them in a generic way, the compiler has about all the information it can have, enabling thorough optimization. Thanks to template implementations.
Now, if for example both list and vector would implement an abstract OO interface like push_backable, and you would use an abstract pointer (push_backable*)->push_back(...) in your code, the compiler would lose a lot of information and thus opportunities for optimization.
These are typical operations that might appear in inner loops and you really want the maximal possible optimization for them. See also Frerich Raabe's answer.

What is so great about STL? [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 9 years ago.
I am a Java developer trying to learn C++. I have many times read on the internet (including Stack Overflow) that STL is the best collections library that you can get in any language. (Sorry, I do not have any citations for that)
However after studying some STL, I am really failing to see what makes STL so special. Would you please shed some light on what sets STL apart from the collection libraries of other languages and make it the best collection library?
What is so great about the STL ?
The STL is great in that it was conceived very early and yet succeeded in using C++ generic programming paradigm quite efficiently.
It separated efficiently the data structures: vector, map, ... and the algorithms to operate on them copy, transform, ... taking advantage of templates to do so.
It neatly decoupled concerns and provided generic containers with hooks of customization (Comparator and Allocator template parameters).
The result is very elegant (DRY principle) and very efficient thanks to compiler optimizations so that hand-generated algorithms for a given container are unlikely to do better.
It also means that it is easily extensible: you can create your own container with the interface you wish, as long as it exposes STL-compliant iterators you'll be able to use the STL algorithms with it!
And thanks to the use of traits, you can even apply the algorithms on C-array through plain pointers! Talk about backward compatibility!
However, it could (perhaps) have been better...
What is not so great about the STL ?
It really pisses me off that one always have to use the iterators, I'd really stand for being able to write: std::foreach(myVector, [](int x) { return x+1;}); because face it, most of the times you want to iterate over the whole of the container...
But what's worse is that because of that:
set<int> mySet = /**/;
set<int>::const_iterator it = std::find(mySet.begin(), mySet.end(), 1005); // [1]
set<int>::const_iterator it = mySet.find(1005); // [2]
[1] and [2] are carried out completely differently, resulting in [1] having O(n) complexity while [2] has O(log n) complexity! Here the problem is that the iterators abstract too much.
I don't mean that iterators are not worthy, I just mean that providing an interface exclusively in terms of iterators was a poor choice.
I much prefer myself the idea of views over containers, for example check out what has been done with Boost.MPL. With a view you manipulate your container with a (lazy) layer of transformation. It makes for very efficient structures that allows you to filter out some elements, transform others etc...
Combining views and concept checking ideas would, I think, produce a much better interface for STL algorithms (and solve this find, lower_bound, upper_bound, equal_range issue).
It would also avoid common mistakes of using ill-defined ranges of iterators and the undefined behavior that result of it...
It's not so much that it's "great" or "the best collections library that you can get in *any* language", but it does have a different philosophy to many other languages.
In particular, the standard C++ library uses a generic programming paradigm, rather than an object-oriented paradigm that is common in languages like Java and C#. That is, you have a "generic" definition of what an iterator should be, and then you can implement the function for_each or sort or max_element that takes any class that implements the iterator pattern, without actually having to inherit from some base "Iterator" interface or whatever.
What I love about the STL is how robust it is. It is easy to extend it. Some complain that it's small, missing many common algorithms or iterators. But this is precisely when you see how easy it is to add in the missing components you need. Not only that, but small is beautiful: you have about 60 algorithms, a handful of containers and a handful of iterators; but the functionality is in the order of the product of these. The interfaces of the containers remain small and simple.
Because it's fashion to write small, simple, modular algorithms it gets easier to spot bugs and holes in your components. Yet, at the same time, as simple as the algorithms and iterators are, they're extraordinarily robust: your algorithms will work with many existing and yet-to-be-written iterators and your iterators work with many existing and yet-to-be-written algorithms.
I also love how simple the STL is. You have containers, you have iterators and you have algorithms. That's it (I'm lying here, but this is what it takes to get comfortable with the library). You can mix different algorithms with different iterators with different containers. True, some of these have constraints that forbid them from working with others, but in general there's a lot to play with.
Niklaus Wirth said that a program is algorithms plus data-structures. That's exactly what the STL is about. If Ruby and Python are string superheros, then C++ and the STL are an algorithms-and-containers superhero.
STL's containers are nice, but they're not much different than you'll find in other programming languages. What makes the STL containers useful is that they mesh beautifully with algorithms. The flexibility provided by the standard algorithms is unmatched in other programming languages.
Without the algorithms, the containers are just that. Containers. Nothing special in particular.
Now if you're talking about container libraries for C++ only, it is unlikely you will find libraries as well used and tested as those provided by STL if nothing else because they are standard.
The STL works beautifully with built-in types. A std::array<int, 5> is exactly that -- an array of 5 ints, which consumes 20 bytes on a 32 bit platform.
java.util.Arrays.asList(1, 2, 3, 4, 5), on the other hand, returns a reference to an object containing a reference to an array containing references to Integer objects containing ints. Yes, that's 3 levels of indirection, and I don't dare predict how many bytes that consumes ;)
This is not a direct answer, but as you're coming from Java I'd like to point this out. By comparison to Java equivalents, STL is really fast.
I did find this page, showing some performance comparisons. Generally Java people are very touchy when it comes to performance conversations, and will claim that all kinds of advances are occurring all the time. However similar advances are also occurring in C/C++ compilers.
Keep in mind that STL is actually quite old now, so other, newer libraries may have specific advantages. Given the age, its' popularity is a testament to how good the original design was.
There are four main reasons why I'd say that STL is (still) awesome:
Speed
STL uses C++ templates, which means that the compiler generates code that is specifically tailored to your use of the library. For example, map will automagically generate a new class to implement a map collection of 'key' type to 'value' type. There is no runtime overhead where the library tries to work out how to efficiently store 'key' and 'value' - this is done at compile time. Due to the elegant design some operations on some types will compile down to single assembly instructions (e.g. increment integer-based iterator).
Efficiency
The collections classes have a notion of 'allocators', which you can either provide yourself or use the library-provided ones which allocate only enough storage to store your data. There is no padding nor wastage. Where a built-in type can be stored more efficiently, there are specializations to handle these cases optimally, e.g. vector of bool is handled as a bitfield.
Exensibility
You can use the Containers (collection classes), Algorithms and Functions provided in the STL on any type that is suitable. If your type can be compared, you can put it into a container. If it goes into a container, it can be sorted, searched, compared. If you provide a function like 'bool Predicate(MyType)', it can be filtered, etc.
Elegance
Other libraries/frameworks have to implement the Sort()/Find()/Reverse() methods on each type of collection. STL implements these as separate algorithms that take iterators of whatever collection you are using and operate blindly on that collection. The algorithms don't care whether you're using a Vector, List, Deque, Stack, Bag, Map - they just work.
Well, that is somewhat of a bold claim... perhaps in C++0x when it finally gets a hash map (in the form of std::unordered_map), it can make that claim, but in its current state, well, I don't buy that.
I can tell you, though, some cool things about it, namely that it uses templates rather than inheritance to achieve its level of flexibility and generality. This has both advantages and disadvantages; a disadvantage is that lots of code gets duplicated by the compiler, and any sort of dynamic runtime typing is very hard to achieve; however, a key advantage is that it is incredibly quick. Because each template specialization is really its own separate class generated by the compiler, it can be highly optimized for that class. Additionally, many of the STL algorithms that operate on STL containers have general definitions, but have specializations for special cases that result in incredibly good performance.
STL gives you the pieces.
Languages and their environments are built from smaller component pieces, sometimes via programming language constructs, sometimes via cut-and-paste. Some languages give you a sealed box - Java's collections, for instance. You can do what they allow, but woe betide you if you want to do something exotic with them.
The STL gives you the pieces that the designers used to build its more advanced functionality. Directly exposing the iterators, algorithms, etc. give you an abstract but highly flexible way of recombining core data structures and manipulations in whatever way is suitable for solving your problem. While Java's design probably hits the 90-95% mark for what you need from data structures, the STL's flexibility raises it to maybe 99%, with the iterator abstraction meaning you're not completely on your own for the remaining 1%.
When you combine that with its speed and other extensibility and customizabiltiy features (allocators, traits, etc.), you have a quite excellent package. I don't know that I'd call it the best data structures package, but certainly a very good one.
Warning: percentages totally made up.
Unique because it
focuses on basic algorithms instead of providing ready-to-use solutions to specific application problems.
uses unique C++ features to implement those algorithms.
As for being best... There is a reason why the same approach wasn't (and probably won't) ever followed by any other language, including direct descendants like D.
The standard C++ library's approach to collections via iterators has come in for some constructive criticism recently. Andrei Alexandrescu, a notable C++ expert, has recently begun working on a new version of a language called D, and describes his experiences designing collections support for it in this article.
Personally I find it frustrating that this kind of excellent work is being put into yet another programming language that overlaps hugely with existing languages, and I've told him so! :) I'd like someone of his expertise to turn their hand to producing a collections library for the so-called "modern languages" that are already in widespread use, Java and C#, that has all the capabilities he thinks are required to be world-class: the notion of a forward-iterable range is already ubiquitous, but what about reverse iteration exposed in an efficient way? What about mutable collections? What about integrating all this smoothly with Linq? etc.
Anyway, the point is: don't believe anyone who tells you that the standard C++ way is the holy grail, the best it could possibly be. It's just one way among many, and has at least one obvious drawback: the fact that in all the standard algorithms, a collection is specified by two separate iterators (begin and end) and hence is clumsy to compose operations on.
Obviously C++, C#, and Java can enter as many pissing contests as you want them to. The clue as to why the STL is at least somewhat great is that Java was initially designed and implemented without type-safe containers. Then Sun decided/realised people actually need them in a typed language, and added generics in 1.5.
You can compare the pros and cons of each, but as to which of the three languages has the "greatest" implementation of generic containers - that is solely a pissing contest. Greatest for what? In whose opinion? Each of them has the best libraries that the creators managed to come up with, subject to other constraints imposed by the languages. C++'s idea of generics doesn't work in Java, and type erasure would be sub-standard in typical C++ usage.
The primary thing is, you can use templates to make using containers switch-in/switch-out, without having to resort to the horrendous mess that is Java's interfaces.
If you fail to see what usage the STL has, I recommend buying a book, "The C++ Programming Language" by Bjarne Stroustrup. It pretty much explains everything there is about C++ because he's the dude who created it.

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.