您的位置:首页 > 其它

STL容器 — 顺序容器

2015-09-05 16:45 246 查看
一:顺序容器

三种顺序容器类型:vector、list、deque

三种顺序容器适配器:stack、queue、priority_queue

在顺序容器中添加容器的操作:

c.push_back(t) //尾部添加值为t的元素。return void

c.push_front(t) //在容器c的前端添加值为t的元素。[ 只适用于 list 和 deque ] return void

c.insert(p,t) //在迭代器p所指向的元素前面插入值为 t 的新元素,返回指向新添加元素的迭代器

//此处要注意,在vector中添加元素会导致整个容器的重新加载,这样,该容器涉及的所有迭代器都会失效,即使不需要重新加载整个容器,指向新插入元素后面的那个元素的迭代器也会失效。任何insert或push操作都可能导致迭代器失效;

//不要存储end操作符返回的结果,添加或者删除deque或vector容器内的元素都会导致存储的迭代器失效。

c.insert(p,n,t) // 在迭代器p所指向的元素前面插入n 个值为 t 的新元素。 return void

c.insert(p,b,e) // 在迭代器p所指向的元素前面插入由迭代器b e所标记的范围内的元素。return void

list中插入一段元素:

typedef string S;
list<S> lis;
list<S>::iterator iter = lis.begin();
string word;
while (cin >> word)
{
iter = ff.insert(iter, word);// 相当于 lis.push_front(word);
}


void main()
{
vector<int> test;
list<int> lit;
test.push_back(2);
test.push_back(3);//在末尾加入一个元素
test.insert(test.begin(), 1);//在test.begin()位置之前插入一个元素1,返回指向新添加元素的迭代器
//Print(test);// 2 3 1

lit.push_front(1);//在容器的前端添加值为t的元素,返回void ,push_front只适用于list和deque
lit.push_back(3);
lit.insert(lit.begin(), test.begin(),test.begin()+2);
Print(lit);

test.resize(5);// 2 3 1 0 0  调整容器大小
test.resize(7, -1);// 2 3 1 0 0 -1 -1

cout << test.back() << endl; // -1  返回容器最后一个元素的引用
cout<< test.front() << endl; //  1 取第一个元素

//删除容器元素
//删除第一个和最后一个元素
test.pop_back();//删除最后一个元素,返回void;适用于所有顺序容器
lit.pop_front(); //删除第一个元素,返回void;只适用于list和deque

Print(lit);
//删除容器内某一元素 erase() 使用所有顺序容器

list<int>::iterator teit = lit.begin();
list<int>::iterator tert = lit.begin();
tert++; //tert++;
cout << *tert << endl;
list<int>::iterator liIter = find(lit.begin(), lit.end(), 1);
if (liIter != lit.end())
lit.erase(liIter);
cout << *teit << endl;
cout << *tert<< endl;
Print(lit);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: