英文描述参考: www.cplusplus.com 部分解释参考:stackoverflow
std deque 和 vector
They provide a functionality similar to vectors, but with efficient insertion and deletion of elements also at the beginning of the sequence, and not only at its end. But, unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations: accessing elements in a deque by offsetting a pointer to another element causes undefined behavior.
deque和vector非常相似,不同点在于deque支持在头尾插入和删除,而且在两端插入和删除不会导致重新分配空间。vector只能在末尾实现插入和删除。deque不保证连续性存储空间,指针偏置可能导致获取不到元素。
根据以上性质可知,deque除了有push_back,pop_back还有push_front,pop_front。
vector::size()和deque::size()都返回size_type类型的数据。
vector::front()和vector::begin()的区别在于前者是reference 而后者是iterator。
下面这里例子说明了deque分配内存时是不连续的,如果声明std::vector myvector; 那么&*it
和 &*(it-1)
相差4(int),如果声明std::deque myvector; 那么&*it
和 &*(it-1)
不一定相差4。
#include <iostream>
#include <vector>
#include <deque>
int main ()
{
std::deque<int> myvector;
std::deque<int>::iterator it;
// set some content in the vector:
for (int i=0; i<128; i++) myvector.push_back(i);
std::cout << "size: " << (int) myvector.size() << '\n';
it=myvector.end();
std::cout << "it: " << &*it << '\n';
it--;
std::cout << "it: " << &*it << '\n';
std::cout << "max_size: " << (int) myvector.max_size() << '\n';
return 0;
}
deque::push_front的例子
// deque::push_front
#include <iostream>
#include &l