> but...recently learned about vectors which are as fast as arrays?
> but doesn't have a fixed size?
Yes.
std::vector<> is at least as fast as a C-style resizeable array.
> then why does lists even exist?
std::list<> exists because it has two properties that
std::vector<> does not have:
a. Addition, removal and moving the elements within the list or across several (allocator-compatible) lists does not invalidate iterators, pointers or references to elements in the list. An iterator or reference is invalidated only when the element referred to is deleted.
b.
std::list<> has strong exception guarantees (commit-or-rollback) for some operations for which
std::vector<> and
std::deque<> provide only weak exception guarantees (consistency).
And a third, insert/erase performance, which would be relevant for monstrously large sequences.
Compared to other base standard sequence containers (array, vector and deque), lists perform generally better in inserting, extracting and moving elements in any position within the container for which an iterator has already been obtained |
Unfortunately, reality is often quite different from what career-teachers teach in classrooms. The value of N (the size of the sequence) above which
std::list<> begins to outperform
std::vector<> with insert/erase operations in arbitrary positions is so high that it is seldom encountered in practice. (This has become particularly true after C++11 and the advent of move semantics.)
Stroustrup gives an example:
http://www.cplusplus.com/forum/general/155310/#msg800593
It is quite easy to construct a similar example using a non-trivially copyable, but moveable type like
std::string and measure
std::list<> vs.
std::vector<> performance.
If performance is important for the program, measure it. One measurement for the typical use-case in a program is more valuable than a thousand opinions.