deque(n):双端队列 emplace(v):安放 assign(v):分配、布置
1 顺序容器
一个容器是一些特定类型对象的集合。 容器是标准库中提供的数据结构(本质是数组扩展的vector、deque、array、string 和 指针扩展的list、forward_list) 顺序容器提供控制元素存储和访问顺序的能力,这种顺序与元素加入容器时的位置相对应。  2 顺序容器的接口(详见P295)
  ①构造函数:
C c;
C c1(c2);
C c(b, e);
C c(a, b, c);
②赋值函数:
c.assign(b, e);
c1 = c2;
c1 = {a, b, c...};
a.swap(b);
swap(a, b);
③获取迭代器: 返回指向c的首元素和尾元素之后位置的迭代器,因为对于容器迭代器区间是[begin,end)左闭右开的。
c.begin(), c.end()
返回const_iterator
c.cbegin(), c.cend()
3 反向迭代器:
反向迭代器详解 ①反向迭代器的模板类定义在 < iterator> 头文件,并位于 std 命名空间中。
reverse_iterator
const_reverse_iterator
c.rbegin()
c.crend()
c.crbegin(),c.crend()
 ②反向迭代器自带base()函数,其基准迭代器为正序,且向右偏移1个元素 s.rbegin().base() == s.end() s.rend().base() == s.begin()
③除了常规的正/反向迭代器begin()、end()、rbegin()、rend()、crbegin()、crend()外,可以通过find函数找到元素,并定义正/反向迭代器指向它
string::reverse_iterator rcomma = find(line.rbegin(), line.rend(), ',');
④反向迭代器++,迭代器逆序前进1 ⑤利用反向迭代器逆序排列
sort(vec.begin(), vec.end());
sort(vec.rbegin(), vec.rend());
4 顺序容器操作实例
#include <iostream>
#include <list>
#include <deque>
using namespace std;
template <class T>
void printContainer(const char* msg, const T& s) {
cout << msg << ": ";
copy(s.begin(), s.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
int main() {
deque<int> s;
for (int i = 0; i < 10; i++) {
int x;
cin >> x;
s.push_front(x);
}
printContainer("deque at first: ", s);
list<int> l(s.rbegin(), s.rend());
printContainer("list at first: ", l);
list<int>::iterator iter = l.begin();
while (iter != l.end()) {
int v = *iter;
iter = l.erase(iter);
l.insert(++iter, v);
}
printContainer("list at last: ", l);
s.assign(l.begin(), l.end());
printContainer("deque at last: ", s);
return 0;
}
TIPS: 不用常规方法交换相邻元素是因为迭代器只是泛型的指针,未重载时不能像普通指针一样使用+、=等运算符。 通常使用迭代器特殊函数进行运算。
以下不可行:
while (iter != l.end()) {
int v = *iter;
*iter = *(iter + 1);
*(iter + 1) = v;
iter += 2;
}
5 顺序容器的特征(vector、deque、list、forward_list、array)
向量与双端队列   随机访问速度:vector > deque > > list/forward_list vector在尾部插入/删除元素快,deque在头部和尾部插入/删除元素快. vector、deque在中间插入/删除元素慢,list/forward_list在任何位置插入/删除元素快
#include <iostream>
#include <vector>
#include <deque>
#include <algorithm>
using namespace std;
int main() {
istream_iterator<int> i1(cin), i2;
vector<int> s1(i1, i2);
sort(s1.begin(), s1.end());
deque<int> s2;
for (vector<int>::iterator iter = s1.begin(); iter != s1.end(); ++iter) {
if (*iter % 2 == 0) {
s2.push_back(*iter);
}
else
s2.push_front(*iter);
}
copy(s2.begin(), s2.end(), ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
|