您的位置:首页 > 编程语言 > C语言/C++

C++ list容器使用

2014-10-21 16:04 459 查看
//----------------------------------------------------

//AUTHOR: lanyang123456

//DATE: 2014-10-21

//----------------------------------------------------

#include <iostream>

#include <list>

using namespace std;

int main()

{

list<int> L;

L.push_back(0);              // Insert a new element at the end

L.push_front(0);             // Insert a new element at the beginning

L.insert(++L.begin(),2);     // Insert "2" before position of first argument

// (Place before second argument)

L.push_back(5);

L.push_back(6);

list<int>::iterator i;

for(i=L.begin(); i != L.end(); ++i) cout << *i << " ";

cout << endl;

return 0;

}


$ g++ -o test list.cpp

$ ./test

0 2 0 5 6

再举一个字符串的例子

#include <iostream>

#include <list>

using namespace std;

int main()

{

list<string> L;

L.push_back("Tom");              // Insert a new element at the end

L.push_front("Jerry");             // Insert a new element at the beginning

L.insert(++L.begin(), "Mily");     // Insert "2" before position of first argument

// (Place before second argument)

L.push_back("Alex");

L.push_back("Jack");

cout<<"list size = "<<L.size()<<endl;
cout<<"list max_size = "<<L.max_size()<<endl;

list<string>::iterator iter;

for(iter = L.begin(); iter != L.end(); ++iter)
cout<<*iter<<endl;

L.erase(--iter);//remove the last one
cout<<"------after erase---------"<<endl;
cout<<"list size = "<<L.size()<<endl;
cout<<"list max_size = "<<L.max_size()<<endl;

for(iter = L.begin(); iter != L.end(); ++iter)
cout<<*iter<<endl;

return 0;

}

/*

$ ./test
list size = 5
list max_size = 768614336404564650
Jerry
Mily
Tom
Alex
Jack
------after erase---------
list size = 4
list max_size = 768614336404564650
Jerry
Mily
Tom
Alex

*/


参考

http://blog.csdn.net/whz_zb/article/details/6831817

http://blog.chinaunix.net/uid-26527046-id-3465518.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: