By default, use vector as the default sequential container in C++. This is the equivalent of List<T> in other languages.
vector<string> v;
v.push_back( "Geddy Lee" );
Use map (not unordered_map) as the default associative container. Use set, multimap, multiset for degenerate & multi cases.
map<string, string> phone_book;
// ...
phone_book["Alex Lifeson"] = "+1 (416) 555-1212";
When performance optimization is needed, consider using:
-
the array type when embedding is important - for example, as a class member.
-
unordered associative containers (unordered_map, et al.): Lower per-element overhead (major) and constant-time lookup (potentially major, sometimes minor). Harder to use correctly and efficiently, because of inconveniences and sharp edges.
-
sorted vector. (See: Algorithms.)
Don’t use C arrays. (For older APIs, use f( vec.data(), vec.size() ); .)
For another article about containers, see STL Containers.
The following tables show the container sizes, in bytes, for x86 and x64 platforms. (For these purposes, 32-bit ARM is equivalent to x86.) These tables cover release mode, because debug mode contains checking machinery that consumes space and time. The separate columns are for [!INCLUDEcpp_orcas_long] SP1, where _SECURE_SCL defaulted to 1, and for [!INCLUDEcpp_orcas_long] SP1 with _SECURE_SCL manually set to 0 for maximum speed. Visual C++ in Visual Studio 2010, [!INCLUDEcpp_dev11_long], and [!INCLUDEcpp_dev12_long] default _SECURE_SCL to 0 (now known as _ITERATOR_DEBUG_LEVEL).
| x86 Container Sizes (Bytes) | VC9 SP1 | VC9 SP1 SCL=0 |
VC10 | VC11 |
|---|---|---|---|---|
| vector<int> | 24 | 16 | 16 | 12 |
| array<int, 5> | 20 | 20 | 20 | 20 |
| deque<int> | 32 | 32 | 24 | 20 |
| forward_list<int> | N/A | N/A | 8 | 4 |
| list<int> | 28 | 12 | 12 | 8 |
| priority_queue<int> | 28 | 20 | 20 | 16 |
| queue<int> | 32 | 32 | 24 | 20 |
| stack<int> | 32 | 32 | 24 | 20 |
| pair<int, int> | 8 | 8 | 8 | 8 |
| tuple<int, int, int> | 16 | 16 | 16 | 12 |
| map<int, int> | 32 | 12 | 16 | 8 |
| multimap<int, int> | 32 | 12 | 16 | 8 |
| set<int> | 32 | 12 | 16 | 8 |
| multiset<int> | 32 | 12 | 16 | 8 |
| hash_map<int, int> | 72 | 44 | 44 | 32 |
| hash_multimap<int, int> | 72 | 44 | 44 | 32 |
| hash_set<int> | 72 | 44 | 44 | 32 |
| hash_multiset<int> | 72 | 44 | 44 | 32 |
| unordered_map<int, int> | 72 | 44 | 44 | 32 |
| unordered_multimap<int, int> | 72 | 44 | 44 | 32 |
| unordered_set<int> | 72 | 44 | 44 | 32 |
| ordered_multiset<int> | 72 | 44 | 44 | 32 |
| string | 28 | 28 | 28 | 24 |
| wstring | 28 | 28 | 28 | 24 |
Welcome Back to C++
C++ Language Reference
C++ Standard Library
