基本容器有:
vector: flexible sized array, random access
deque: double-ended queue, random access
list: doubly linked list, bi-directional sequential access
forward_list: singly linked list, single directional sequential access
array: fixed size, random access
string: similar to vector, contain characters, fast access
使用原则:
unless you have a reason to use another container, use a vector;
if you have lots of small elements or space overhead matters, don’t use list or forward_list;
require random access, use vector or deque;
need to insert in the middle, use list or forward_list;
insert or delete in the front or back, but not middle, use deque;
container 通用初始化方法:
以string为例:
string s1;
string s2(s1); // == string s2 = s1;
string s3(s2.begin(), s2.end()); // by two iterators
C c{}; // list initialization
string s4("hello");
string s5 = "hello";
string s6(10, 'c'); // vector is the same
补充string基本操作:
cin >> s;
cout << s;
getline(cin, s);
s.empty();
s.size();
s[i];
s.push_back('s');
s1 + s2; // concatenation s1 and s2
s1 = s2; //replace s1 with s2
s1 == != < <= > >= s2 // comparison
通用iterator迭代器:
list<int>::iterator iter1 = list.begin();
list<int>::iterator iter2 = list.end();
通用assign and swap:
seq.assign(b, e); // b and e is two iterators
seq.assign(il); // replace elements in seq with initializer list il
seq.assign(n, t); // replace seq with n elements with value t
swap(seq1, seq2);
seq1.swap(seq2);
container 通常支持relational operation
但必须是同一种容器以及同一种类型的元素
== != < > <= >=
通用型resize,除了array都能用
list<int> l;
l.resize(n); // 如果n小于l长度,取前n个,否则不够补0;
l.resize(n, m); //当n大于l长度的时候,不够的补为m
deque: 升级版的stack加上queue
empty();
size();
front();
back();
pop_back(), push_back;
pop_front(), pop_front;
insert(b)
erase(b, e)
list:
基本操作同deque,但是list的erase和insert比deque和vector高效很多。
list和forward_list 不支持下标和.at()操作。
forward_list 没有back类型的操作。