c++ 顺序容器

种顺序容器(sequential container)。它将单一类型元素聚集起来成为容器,然后根据位置来存储和访问这些元素,这就是顺序容器。顺序容器的元素排列次序与元素值无关,而是由元素添加到容器里的次序决定。

vector、list 和 deque    

容器内元素的类型约束 

 

• 元素类型必须支持赋值运算。
• 元素类型的对象必须可以复制。

差别在于访问元素的方式,以及添加或删除元素相关操作的运行代价

顺序容器适配器包括 stack、queue 和 priority_queue 类型

#include <vector> #include <list> #include <deque>

vector<string> svec; // empty vector that can hold strings
list<int> ilist; // empty list that can hold ints
deque<Sales_item> items; // empty deque that holds Sales_items 

vector<int> ivec;
vector<int> ivec2(ivec); // ok: ivec is vector<int>
list<int> ilist(ivec); // error: ivec is not list<int>
vector<double> dvec(ivec); // error: ivec holds int not double

// initialize slist with copy of each element of svec
list<string> slist(svec.begin(), svec.end());

// find midpoint in the vector
vector<string>::iterator mid = svec.begin() + svec.size()/2;

// initialize front with first half of svec: The elements up to but not including *mid
deque<string> front(svec.begin(), mid);
// initialize back with second half of svec: The elements *mid through end of svec
deque<string> back(mid, svec.end());

char *words[] = {"stately", "plump", "buck", "mulligan"};
// calculate how many elements in words
size_t words_size = sizeof(words)/sizeof(char *);
// use entire array to initialize words2
list<string> words2(words, words + words_size);

分配和初始化指定数目的元素 

const list<int>::size_type list_size = 64;
list<string> slist(list_size, "eh?"); // 64 strings, each is eh?

 

 

 

 

posted on 2012-11-10 16:14  GIS-MAN  阅读(224)  评论(0编辑  收藏  举报

导航