第五讲 list

STL 中的list容器

 1 //对已string型list进行添加,删除,查找,插入操作
 2 #include "stdafx.h"
 3 #include <iostream>
 4 #include <string>
 5 #include <list>
 6 using namespace std;
 7 
 8 int main()
 9 {
10     list<string> oList;
11     //list不能对相应的对象进行直接操作,只能通过算法或迭代器
12     //oList[0] = "www.jiesoon.com";  //不行
13 
14     //list没有预留空间
15     //oList.capacity();            //没有这个函数
16     
17     //给oList对象添加元素
18     oList.push_back("3.jiesoon.com");
19     oList.push_front("2.jiesoon.com");
20     oList.push_back("4.jiesoon.com");
21     oList.push_front("1.jiesoon.com");
22 
23     list<string>::iterator itList = oList.begin();
24     for(; itList != oList.end(); ++itList){
25         cout<< *itList << endl;    
26     }
27     
28     cout<< "oList存有的元素:" << oList.size() << endl;
29 
30     cout << "**********************************************" << endl;
31 
32     //list 是个双向链表    vector deque 也可以用迭代器双向访问
33     itList = oList.begin();
34     //itList += 2;    //不可以,list 不是一个连续的容器
35     ++itList;
36     ++itList;
37     cout << *itList << endl;
38 
39     --itList;
40     cout << *itList << endl;
41 
42     cout << "**********************************************" << endl;
43     //插入数据 (不同于vector,deque 在不同位置插入数据有着一样的效率)
44     itList = oList.begin();
45     oList.insert(itList,"0.jiesoon.com");
46     for(itList = oList.begin(); itList != oList.end(); ++itList){
47         cout<< *itList << endl;    
48     }
49 
50     cout << "**********************************************" << endl;
51     //删除数据方法①
52     oList.remove("2.jiesoon.com");
53     for(itList = oList.begin(); itList != oList.end(); ++itList){
54         cout<< *itList << endl;    
55     }
56 
57     cout << "**********************************************" << endl;
58     //删除数据方法②
59     itList = oList.begin();
60     oList.erase(itList);
61     for(itList = oList.begin(); itList != oList.end(); ++itList){
62         cout<< *itList << endl;    
63     }
64     
65     return 0;
66 }

 

posted @ 2014-06-25 21:57  击进的Cocos  阅读(287)  评论(0编辑  收藏  举报