---
title: "C++ 标准库 vector list map使用方法"
author: "xpp02"
date: "2013-02-02T15:24:00Z"
tags: []
slug: "c-vector-list-map"
draft: false
lastmod: "2013-02-02T21:33:58Z"
id: 1784218
url: "https://xpp02.iteye.com/blog/1784218"
---

**\[cpp]** [view plain](http://blog.csdn.net/monkeyandy/article/details/7600043 "view plain")[copy](http://blog.csdn.net/monkeyandy/article/details/7600043 "copy")

1. List（链表）

List将元素按顺序储存在链表中. 与 向量(vectors)相比, 它允许快速的插入和删除，但是随机访问却比较慢.

list对象函数

assign() 给list赋值  
back() 返回最后一个元素  
begin() 返回指向第一个元素的迭代器  
clear() 删除所有元素  
empty() 如果list是空的则返回true  
end() 返回末尾的迭代器  
erase() 删除一个元素  
front() 返回第一个元素  
get\_allocator() 返回list的配置器  
insert() 插入一个元素到list中  
max\_size() 返回list能容纳的最大元素数量  
merge() 合并两个list  
pop\_back() 删除最后一个元素  
pop\_front() 删除第一个元素  
push\_back() 在list的末尾添加一个元素  
push\_front() 在list的头部添加一个元素  
rbegin() 返回指向第一个元素的逆向迭代器  
remove() 从list删除元素  
remove\_if() 按指定条件删除元素  
rend() 指向list末尾的逆向迭代器  
resize() 改变list的大小  
reverse() 把list的元素倒转  
size() 返回list中的元素个数  
sort() 给list排序  
splice() 合并两个list  
swap() 交换两个list  
unique() 删除list中重复的元素

List实例代码

**\[cpp]** [view plain](http://blog.csdn.net/monkeyandy/article/details/7600043 "view plain")[copy](http://blog.csdn.net/monkeyandy/article/details/7600043 "copy")

01. #include&lt;iostream&gt;
02. #include&lt;list&gt;
03. #include&lt;numeric&gt;
04. #include&lt;algorithm&gt;
05. usingnamespacestd;
06. //创建一个list容器的实例LISTINT
07. typedeflist&lt;int&gt;LISTINT;
08. //创建一个list容器的实例LISTCHAR
09. typedeflist&lt;char&gt;LISTCHAR;
10. intmain(void)
11. {
12. //--------------------------
13. //用list容器处理整型数据
14. //--------------------------
15. //用LISTINT创建一个名为listOne的list对象
16. LISTINTlistOne;
17. //声明i为迭代器
18. LISTINT::iteratori;
19. //从前面向listOne容器中添加数据
20. listOne.push\_front(2);
21. listOne.push\_front(1);
22. //从后面向listOne容器中添加数据
23. listOne.push\_back(3);
24. listOne.push\_back(4);
25. //从前向后显示listOne中的数据
26. cout&lt;&lt;"listOne.begin()---listOne.end():"&lt;&lt;endl;
27. for(i=listOne.begin();i!=listOne.end();++i)
28. cout&lt;&lt;\*i&lt;&lt;"";
29. cout&lt;&lt;endl;
30. //从后向后显示listOne中的数据
31. LISTINT::reverse\_iteratorir;
32. cout&lt;&lt;"listOne.rbegin()---listOne.rend():"&lt;&lt;endl;
33. for(ir=listOne.rbegin();ir!=listOne.rend();ir++){
34. cout&lt;&lt;\*ir&lt;&lt;"";
35. }
36. cout&lt;&lt;endl;
37. //使用STL的accumulate(累加)算法
38. intresult=accumulate(listOne.begin(),listOne.end(),0);
39. cout&lt;&lt;"Sum="&lt;&lt;result&lt;&lt;endl;
40. cout&lt;&lt;"------------------"&lt;&lt;endl;
41. //--------------------------
42. //用list容器处理字符型数据
43. //--------------------------
44. //用LISTCHAR创建一个名为listOne的list对象
45. LISTCHARlistTwo;
46. //声明i为迭代器
47. LISTCHAR::iteratorj;
48. //从前面向listTwo容器中添加数据
49. listTwo.push\_front('A');
50. listTwo.push\_front('B');
51. //从后面向listTwo容器中添加数据
52. listTwo.push\_back('x');
53. listTwo.push\_back('y');
54. //从前向后显示listTwo中的数据
55. cout&lt;&lt;"listTwo.begin()---listTwo.end():"&lt;&lt;endl;
56. for(j=listTwo.begin();j!=listTwo.end();++j)
57. cout&lt;&lt;char(\*j)&lt;&lt;"";
58. cout&lt;&lt;endl;
59. //使用STL的max\_element算法求listTwo中的最大元素并显示
60. j=max\_element(listTwo.begin(),listTwo.end());
61. cout&lt;&lt;"ThemaximumelementinlistTwois:"&lt;&lt;char(\*j)&lt;&lt;endl;
62. return0;
63. }

vector相关用法

vector的初始化大小和赋初值  
(1)vector&lt; 类型 &gt; 标识符 ;  
(2)vector&lt; 类型 &gt; 标识符(最大容量) ；  
(3)vector&lt; 类型 &gt; 标识符（最大容量，初始所有值）；  
vector&lt; int &gt; arry(5, 1);  
注：定义一个大小为5的数组，并将每个值都赋为1；  
int i;  
for( i = 0; i &lt; 5; i ++ )  
cout &lt;&lt; arry\[i] &lt;&lt; " ";  
输出结果为：1 1 1 1 1  
同理定义其他类型的：  
vector&lt;char&gt; arry(3, '\*');  
定义二维的vector:  
vector&lt; vector &lt;int&gt;&gt; Arry（10， vector&lt;int&gt;(0)）;

使用数组对C++ Vector进行初始化  
int i\[10] ={1,2,3,4,5,6,7,78,8} ;  
///第一种  
vector&lt;int&gt; vi(i+1,i+3); ///从第2个元素到第三个元素  
for(vector &lt;int&gt;::interator it = vi.begin() ;  
it != vi.end() ; it++)  
{  
cout &lt;&lt; \*it &lt;&lt;" " ;  
}

vector 的数据的存入和输出：

**\[cpp]** [view plain](http://blog.csdn.net/monkeyandy/article/details/7600043 "view plain")[copy](http://blog.csdn.net/monkeyandy/article/details/7600043 "copy")

01. #include&lt;iostream&gt;
02. #include&lt;vector&gt;
03. #include&lt;algorithm&gt;
04. #include&lt;cstdlib&gt;
05. usingnamespacestd;
06. intmain(void)
07. {
08. vector&lt;int&gt;num;//STL中的vector容器
09. intelement;
10. //从标准输入设备读入整数，
11. //直到输入的是非整型数据为止
12. while(cin&gt;&gt;element)//ctrl+Z结束输入
13. num.push\_back(element);
14. //STL中的排序算法
15. sort(vi.begin(),vi.end());///从小到大
16. reverse(vi.begin(),vi.end())///从大道小
17. //将排序结果输出到标准输出设备
18. for(inti=0;i&lt;num.size();i++)
19. cout&lt;&lt;num\[i]&lt;&lt;"\\n";
20. //也可以这样做
21. system("pause");
22. return0;
23. }

对于二维vector的定义。  
1)定义一个10个vector元素，并对每个vector符值1-10。

**\[cpp]** [view plain](http://blog.csdn.net/monkeyandy/article/details/7600043 "view plain")[copy](http://blog.csdn.net/monkeyandy/article/details/7600043 "copy")

01. #include&lt;stdio.h&gt;
02. #include&lt;vector&gt;
03. #include&lt;iostream&gt;
04. usingnamespacestd;
05. intmain()
06. {
07. inti=0,j=0;
08. //定义一个二维的动态数组，有10行，每一行是一个用一个vector存储这一行的数据。
09. 所以每一行的长度是可以变化的。之所以用到vector&lt;int&gt;(0)是对vector初始化，否则不能对vector存入元素。
10. vector&lt;vector&lt;int&gt;&gt;Array(10,vector&lt;int&gt;(0));
11. for(j=0;j&lt;10;j++)
12. {
13. for(i=0;i&lt;9;i++)
14. {
15. Array\[j].push\_back(i);
16. }
17. }
18. for(j=0;j&lt;10;j++)
19. {
20. for(i=0;i&lt;Array\[j].size();i++)
21. {
22. cout&lt;&lt;Array\[j]\[i]&lt;&lt;"";
23. }
24. cout&lt;&lt;endl;
25. }
26. }

定义一个行列都是变化的数组。

**\[cpp]** [view plain](http://blog.csdn.net/monkeyandy/article/details/7600043 "view plain")[copy](http://blog.csdn.net/monkeyandy/article/details/7600043 "copy")

01. #include&lt;stdio.h&gt;
02. #include&lt;vector&gt;
03. #include&lt;iostream&gt;
04. usingnamespacestd;
05. voidmain()
06. {
07. inti=0,j=0;
08. vector&lt;vector&lt;int&gt;&gt;Array;
09. vector&lt;int&gt;line;
10. for(j=0;j&lt;10;j++)
11. {
12. Array.push\_back(line);//要对每一个vector初始化，否则不能存入元素。
13. for(i=0;i&lt;9;i++)
14. {
15. Array\[j].push\_back(i);
16. }
17. }
18. for(j=0;j&lt;10;j++)
19. {
20. for(i=0;i&lt;Array\[j].size();i++)
21. {
22. cout&lt;&lt;Array\[j]\[i]&lt;&lt;"";
23. }
24. cout&lt;&lt;endl;

**\[cpp]** [view plain](http://blog.csdn.net/monkeyandy/article/details/7600043 "view plain")[copy](http://blog.csdn.net/monkeyandy/article/details/7600043 "copy")

1. &lt;spanstyle="white-space:pre"&gt;&lt;/span&gt;return0;
2. }
3. }

使 用 vettor erase 指定元素

**\[cpp]** [view plain](http://blog.csdn.net/monkeyandy/article/details/7600043 "view plain")[copy](http://blog.csdn.net/monkeyandy/article/details/7600043 "copy")

01. #include&lt;iostream&gt;
02. #include&lt;vector&gt;
03. usingnamespacestd;
04. intmain()
05. {
06. vector&lt;int&gt;arr;
07. arr.push\_back(6);
08. arr.push\_back(8);
09. arr.push\_back(3);
10. arr.push\_back(8);
11. for(vector&lt;int&gt;::iteratorit=arr.begin();it!=arr.end();)
12. {
13. if(\*it==8)
14. {
15. it=arr.erase(it);
16. }
17. else
18. {
19. ++it;
20. }
21. }
22. cout&lt;&lt;"Afterremove8:\\n";
23. for(vector&lt;int&gt;::iteratorit=arr.begin();it&lt;arr.end();++it)
24. {
25. cout&lt;&lt;\*it&lt;&lt;"";
26. }
27. cout&lt;&lt;endl;
28. return0;
29. }

附：  
1.push\_back 在数组的最后添加一个数据  
2.pop\_back 去掉数组的最后一个数据  
3.at 得到编号位置的数据  
4.begin 得到数组头的指针  
5.end 得到数组的最后一个单元+1的指针  
6．front 得到数组头的引用  
7.back 得到数组的最后一个单元的引用  
8.max\_size 得到vector最大可以是多大  
9.capacity 当前vector分配的大小  
10.size 当前使用数据的大小  
11.resize 改变当前使用数据的大小，如果它比当前使用的大，者填充默认值  
v.resize(2\*v.size, 99) 将v的容量翻倍(并把新元素的值初始化为99)  
12.reserve 改变当前vecotr所分配空间的大小  
13.erase 删除指针指向的数据项  
14.clear 清空当前的vector  
15.rbegin 将vector反转后的开始指针返回(其实就是原来的end-1)  
16.rend 将vector反转构的结束指针返回(其实就是原来的begin-1)  
17.empty 判断vector是否为空  
18.swap 与另一个vector交换数据

map用法

1、map简介

map是一类关联式容器。它的特点是增加和删除节点对迭代器的影响很小，除了那个操作节点，对其他的节点都没有什么影响。对于迭代器来说，可以修改实值，而不能修改key。

2、map的功能

自动建立Key － value的对应。key 和 value可以是任意你需要的类型。  
根据key值快速查找记录，查找的复杂度基本是Log(N)，如果有1000个记录，最多查找10次，1,000,000个记录，最多查找20次。  
快速插入Key - Value 记录。  
快速删除记录  
根据Key 修改value记录。  
遍历所有记录。  
3、使用map

使用map得包含map类所在的头文件

#include &lt;map&gt; //注意，STL头文件没有扩展名.h

map对象是模板类，需要关键字和存储对象两个模板参数：

std:map&lt;int, string&gt; personnel;

这样就定义了一个用int作为索引,并拥有相关联的指向string的指针.

为了使用方便，可以对模板类进行一下类型定义，

typedef map&lt;int, CString&gt; UDT\_MAP\_INT\_CSTRING;

UDT\_MAP\_INT\_CSTRING enumMap;

4、在map中插入元素

改变map中的条目非常简单，因为map类已经对\[]操作符进行了重载

enumMap\[1] = "One";

enumMap\[2] = "Two";

.....

这样非常直观，但存在一个性能的问题。插入2时,先在enumMap中查找主键为2的项，没发现，然后将一个新的对象插入enumMap，键是2，值是一个空字符串，插入完成后，将字符串赋为"Two"; 该方法会将每个值都赋为缺省值，然后再赋为显示的值，如果元素是类对象，则开销比较大。我们可以用以下方法来避免开销：

enumMap.insert(map&lt;int, CString&gt; :: value\_type(2, "Two"))

5、查找并获取map中的元素

下标操作符给出了获得一个值的最简单方法：

CString tmp = enumMap\[2];

但是,只有当map中有这个键的实例时才对，否则会自动插入一个实例，值为初始化值。

我们可以使用Find()和Count()方法来发现一个键是否存在。

查找map中是否包含某个关键字条目用find()方法，传入的参数是要查找的key，在这里需要提到的是begin()和end()两个成员，分别代表map对象中第一个条目和最后一个条目，这两个数据的类型是iterator.

int nFindKey = 2; //要查找的Key

//定义一个条目变量(实际是指针)

UDT\_MAP\_INT\_CSTRING::iterator it= enumMap.find(nFindKey);

if(it == enumMap.end()) {

//没找到

}

else {

//找到

}

通过map对象的方法获取的iterator数据类型是一个std::pair对象，包括两个数据 iterator-&gt;first 和 iterator-&gt;second 分别代表关键字和存储的数据

6、从map中删除元素

移除某个map中某个条目用erase()

该成员方法的定义如下

iterator erase(iterator it); //通过一个条目对象删除  
iterator erase(iterator first, iterator last); //删除一个范围  
size\_type erase(const Key& key); //通过关键字删除  
clear()就相当于 enumMap.erase(enumMap.begin(), enumMap.end());

C++ STL map的使用

以下是对C++中STL map的插入，查找，遍历及删除的例子：

**\[cpp]** [view plain](http://blog.csdn.net/monkeyandy/article/details/7600043 "view plain")[copy](http://blog.csdn.net/monkeyandy/article/details/7600043 "copy")

01. #include&lt;map&gt;
02. #include&lt;string&gt;
03. #include&lt;iostream&gt;
04. usingnamespacestd;
05. voidmap\_insert(map&lt;string,string&gt;\*mapStudent,stringindex,stringx)
06. {
07. mapStudent-&gt;insert(map&lt;string,string&gt;::value\_type(index,x));
08. }
09. intmain(intargc,char\*\*argv)
10. {
11. chartmp\[32]="";
12. map&lt;string,string&gt;mapS;
13. //insertelement
14. map\_insert(&mapS,"192.168.0.128","xiong");
15. map\_insert(&mapS,"192.168.200.3","feng");
16. map\_insert(&mapS,"192.168.200.33","xiongfeng");
17. map&lt;string,string&gt;::iteratoriter;
18. cout&lt;&lt;"WeHaveThirdElement:"&lt;&lt;endl;
19. cout&lt;&lt;"-----------------------------"&lt;&lt;endl;
20. //findelement
21. iter=mapS.find("192.168.0.33");
22. if(iter!=mapS.end()){
23. cout&lt;&lt;"findtheelememt"&lt;&lt;endl;
24. cout&lt;&lt;"Itis:"&lt;&lt;iter-&gt;second&lt;&lt;endl;
25. }else{
26. cout&lt;&lt;"notfindtheelement"&lt;&lt;endl;
27. }
28. //seeelement
29. for(iter=mapS.begin();iter!=mapS.end();iter){
30. cout&lt;&lt;"|"&lt;&lt;iter-&gt;first&lt;&lt;"|"&lt;&lt;iter-&gt;
31. second&lt;&lt;"|"&lt;&lt;endl;
32. }
33. cout&lt;&lt;"-----------------------------"&lt;&lt;endl;
34. map\_insert(&mapS,"192.168.30.23","xf");
35. cout&lt;&lt;"AfterWeInsertOneElement:"&lt;&lt;endl;
36. cout&lt;&lt;"-----------------------------"&lt;&lt;endl;
37. for(iter=mapS.begin();iter!=mapS.end();iter){
38. cout&lt;&lt;"|"&lt;&lt;iter-&gt;first&lt;&lt;"|"&lt;&lt;iter-&gt;
39. second&lt;&lt;"|"&lt;&lt;endl;
40. }
41. cout&lt;&lt;"-----------------------------"&lt;&lt;endl;
42. //deleteelement
43. iter=mapS.find("192.168.200.33");
44. if(iter!=mapS.end()){
45. cout&lt;&lt;"findtheelement:"&lt;&lt;iter-&gt;first&lt;&lt;endl;
46. cout&lt;&lt;"deleteelement:"&lt;&lt;iter-&gt;first&lt;&lt;endl;
47. cout&lt;&lt;"================================="&lt;&lt;endl;
48. mapS.erase(iter);
49. }else{
50. cout&lt;&lt;"notfindtheelement"&lt;&lt;endl;
51. }
52. for(iter=mapS.begin();iter!=mapS.end();iter){
53. cout&lt;&lt;"|"&lt;&lt;iter-&gt;first&lt;&lt;"|"&lt;&lt;iter-&gt;
54. second&lt;&lt;"|"&lt;&lt;endl;
55. }
56. cout&lt;&lt;"================================="&lt;&lt;endl;
57. return0;
58. }

本文参考：

[http://blog.csdn.net/lyn\_bigdream/article/details/6601510](http://blog.csdn.net/lyn_bigdream/article/details/6601510)

[http://blog.sina.com.cn/s/blog\_63a1163f0100jxr9.html](http://blog.sina.com.cn/s/blog_63a1163f0100jxr9.html)

[http://wmnmtm.blog.163.com/blog/static/38245714201072310131130/](http://wmnmtm.blog.163.com/blog/static/38245714201072310131130/)