C++ 标准库 vector list map使用方法

来源:互联网 发布:notes plus 知乎 编辑:程序博客网 时间:2024/06/02 13:12
[cpp] view plaincopy
  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 plaincopy
  1. #include <iostream>  
  2. #include <list>  
  3. #include <numeric>  
  4. #include <algorithm>  
  5.   
  6. using namespace std;  
  7.   
  8. //创建一个list容器的实例LISTINT  
  9. typedef list<int> LISTINT;  
  10.   
  11. //创建一个list容器的实例LISTCHAR  
  12. typedef list<char> LISTCHAR;  
  13.   
  14. int main(void)  
  15. {  
  16.     //--------------------------  
  17.     //用list容器处理整型数据  
  18.     //--------------------------  
  19.     //用LISTINT创建一个名为listOne的list对象  
  20.     LISTINT listOne;  
  21.     //声明i为迭代器  
  22.     LISTINT::iterator i;  
  23.   
  24.     //从前面向listOne容器中添加数据  
  25.     listOne.push_front (2);  
  26.     listOne.push_front (1);  
  27.   
  28.     //从后面向listOne容器中添加数据  
  29.     listOne.push_back (3);  
  30.     listOne.push_back (4);  
  31.   
  32.     //从前向后显示listOne中的数据  
  33.     cout<<"listOne.begin()--- listOne.end():"<<endl;  
  34.     for (i = listOne.begin(); i != listOne.end(); ++i)  
  35.         cout << *i << " ";  
  36.     cout << endl;  
  37.   
  38.     //从后向后显示listOne中的数据  
  39.     LISTINT::reverse_iterator ir;  
  40.     cout<<"listOne.rbegin()---listOne.rend():"<<endl;  
  41.     for (ir =listOne.rbegin(); ir!=listOne.rend();ir++) {  
  42.         cout << *ir << " ";  
  43.     }  
  44.     cout << endl;  
  45.   
  46.     //使用STL的accumulate(累加)算法  
  47.     int result = accumulate(listOne.begin(), listOne.end(),0);  
  48.     cout<<"Sum="<<result<<endl;  
  49.     cout<<"------------------"<<endl;  
  50.   
  51.     //--------------------------  
  52.     //用list容器处理字符型数据  
  53.     //--------------------------  
  54.   
  55.     //用LISTCHAR创建一个名为listOne的list对象  
  56.     LISTCHAR listTwo;  
  57.     //声明i为迭代器  
  58.     LISTCHAR::iterator j;  
  59.   
  60.     //从前面向listTwo容器中添加数据  
  61.     listTwo.push_front ('A');  
  62.     listTwo.push_front ('B');  
  63.   
  64.     //从后面向listTwo容器中添加数据  
  65.     listTwo.push_back ('x');  
  66.     listTwo.push_back ('y');  
  67.   
  68.     //从前向后显示listTwo中的数据  
  69.     cout<<"listTwo.begin()---listTwo.end():"<<endl;  
  70.     for (j = listTwo.begin(); j != listTwo.end(); ++j)  
  71.         cout << char(*j) << " ";  
  72.     cout << endl;  
  73.   
  74.     //使用STL的max_element算法求listTwo中的最大元素并显示  
  75.     j=max_element(listTwo.begin(),listTwo.end());  
  76.     cout << "The maximum element in listTwo is: "<<char(*j)<<endl;  
  77.   
  78.     return 0;  
  79. }  


vector相关用法

vector的初始化大小和赋初值
(1)vector< 类型 > 标识符 ;
(2)vector< 类型 > 标识符(最大容量) ;
(3)vector< 类型 > 标识符(最大容量,初始所有值);
vector< int > arry(5, 1);
注:定义一个大小为5的数组,并将每个值都赋为1;
int i;
for( i = 0; i < 5; i ++ )
cout << arry[i] << " ";
输出结果为:1 1 1 1 1
同理定义其他类型的:
vector<char> arry(3, '*');
定义二维的vector:
vector< vector <int>> Arry(10, vector<int>(0));
 
使用数组对C++ Vector进行初始化
int i[10] ={1,2,3,4,5,6,7,78,8} ;  
///第一种   
vector<int> vi(i+1,i+3); ///从第2个元素到第三个元素  
for(vector <int>::interator it = vi.begin() ; 
it != vi.end() ; it++)  
{  
cout << *it <<" " ;   


 vector 的数据的存入和输出:

[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <vector>  
  3. #include <algorithm>  
  4. #include <cstdlib>  
  5. using namespace std;  
  6.    
  7. int main(void)  
  8. {  
  9.    vector<int> num;   // STL中的vector容器  
  10.    int element;  
  11.    
  12.    // 从标准输入设备读入整数,   
  13.    // 直到输入的是非整型数据为止  
  14.    while (cin >> element)     //ctrl+Z 结束输入   
  15.       num.push_back(element);  
  16.    
  17.    // STL中的排序算法  
  18.    sort(vi.begin() , vi.end()); /// 从小到大    
  19.    reverse(vi.begin(),vi.end()) /// 从大道小   
  20.    
  21.    
  22.    // 将排序结果输出到标准输出设备  
  23.    for (int i = 0; i < num.size(); i ++)  
  24.       cout << num[i] << "\n";  
  25.    //也可以这样做  
  26.      
  27.         
  28.    system("pause");  
  29.    return 0;  
  30. }  
 对于二维vector的定义。
1)定义一个10个vector元素,并对每个vector符值1-10。
[cpp] view plaincopy
  1. #include<stdio.h>  
  2. #include<vector>  
  3. #include <iostream>  
  4. using namespace std;  
  5. int main()  
  6. {  
  7.  int i = 0, j = 0;  
  8. //定义一个二维的动态数组,有10行,每一行是一个用一个vector存储这一行的数据。  
  9. 所 以每一行的长度是可以变化的。之所以用到vector<int>(0)是对vector初始化,否则不能对vector存入元素。  
  10.  vector< vector<int> > Array( 10, vector<int>(0) );   
  11. for( j = 0; j < 10; j++ )  
  12.  {  
  13.   for ( i = 0; i < 9; i++ )  
  14.   {  
  15.    Array[ j ].push_back( i );  
  16.   }  
  17.  }  
  18.  for( j = 0; j < 10; j++ )  
  19.  {  
  20.   for( i = 0; i < Array[ j ].size(); i++ )  
  21.   {  
  22.    cout << Array[ j ][ i ] << "  ";  
  23.   }  
  24.   cout<< endl;  
  25.  }  
  26. }  

定义一个行列都是变化的数组。
[cpp] view plaincopy
  1. #include<stdio.h>  
  2. #include<vector>  
  3. #include <iostream>  
  4. using namespace std;  
  5. void main()  
  6. {  
  7.  int i = 0, j = 0;  
  8.  vector< vector<int> > Array;  
  9.  vector< int > line;  
  10.  for( j = 0; j < 10; j++ )  
  11.  {  
  12.   Array.push_back( line );//要对每一个vector初始化,否则不能存入元素。  
  13.   for ( i = 0; i < 9; i++ )  
  14.   {  
  15.    Array[ j ].push_back( i );  
  16.   }  
  17.  }  
  18.  for( j = 0; j < 10; j++ )  
  19.  {  
  20.   for( i = 0; i < Array[ j ].size(); i++ )  
  21.   {  
  22.    cout << Array[ j ][ i ] << "  ";  
  23.   }  
  24.   cout<< endl;  
[cpp] view plaincopy
  1. <span style="white-space:pre">  </span>return 0;  
  2.  }  
  3. }  
使 用 vettor erase 指定元素
[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <vector>  
  3.   
  4. using namespace std;  
  5.   
  6. int   main()  
  7. {  
  8.     vector<int>   arr;  
  9.     arr.push_back(6);  
  10.     arr.push_back(8);  
  11.     arr.push_back(3);  
  12.     arr.push_back(8);  
  13.   
  14.     for(vector<int>::iterator it=arr.begin(); it!=arr.end(); )  
  15.     {  
  16.         if(* it == 8)  
  17.         {  
  18.             it = arr.erase(it);  
  19.         }  
  20.         else  
  21.         {  
  22.             ++it;  
  23.         }  
  24.     }  
  25.   
  26.     cout << "After remove 8:\n";  
  27.   
  28.     for(vector<int>::iterator it = arr.begin(); it < arr.end(); ++it)  
  29.     {  
  30.         cout << * it << " ";  
  31.     }  
  32.     cout << endl;  
  33.     return 0;  
  34. }  
附:
 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 <map> //注意,STL头文件没有扩展名.h

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

std:map<int, string> personnel;

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

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

typedef map<int, CString> 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<int, CString> :: 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->first 和 iterator->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 plaincopy
  1. #include <map>   
  2. #include <string>   
  3. #include <iostream>   
  4. using namespace std;  
  5.   
  6. void map_insert(map < string, string > *mapStudent, string index, string x)   
  7. {   
  8. mapStudent->insert(map < string, string >::value_type(index, x));   
  9. }  
  10.   
  11. int main(int argc, char **argv)   
  12. {   
  13. char tmp[32] = "";   
  14. map < string, string > mapS;  
  15.   
  16. //insert element   
  17. map_insert(&mapS, "192.168.0.128""xiong");   
  18. map_insert(&mapS, "192.168.200.3""feng");   
  19. map_insert(&mapS, "192.168.200.33""xiongfeng");  
  20.   
  21. map < string, string >::iterator iter;  
  22.   
  23. cout << "We Have Third Element:" << endl;   
  24. cout << "-----------------------------" << endl;  
  25.   
  26. //find element   
  27. iter = mapS.find("192.168.0.33");   
  28. if (iter != mapS.end()) {   
  29. cout << "find the elememt" << endl;   
  30. cout << "It is:" << iter->second << endl;   
  31. else {   
  32. cout << "not find the element" << endl;   
  33. }  
  34.   
  35. //see element   
  36. for (iter = mapS.begin(); iter != mapS.end(); iter ) {  
  37.   
  38. cout << "| " << iter->first << " | " << iter->   
  39. second << " |" << endl;  
  40.   
  41. }   
  42. cout << "-----------------------------" << endl;  
  43.   
  44. map_insert(&mapS, "192.168.30.23""xf");  
  45.   
  46. cout << "After We Insert One Element:" << endl;   
  47. cout << "-----------------------------" << endl;   
  48. for (iter = mapS.begin(); iter != mapS.end(); iter ) {  
  49.   
  50. cout << "| " << iter->first << " | " << iter->   
  51. second << " |" << endl;   
  52. }  
  53.   
  54. cout << "-----------------------------" << endl;  
  55.   
  56. //delete element   
  57. iter = mapS.find("192.168.200.33");   
  58. if (iter != mapS.end()) {   
  59. cout << "find the element:" << iter->first << endl;   
  60. cout << "delete element:" << iter->first << endl;   
  61. cout << "=================================" << endl;   
  62. mapS.erase(iter);   
  63. else {   
  64. cout << "not find the element" << endl;   
  65. }   
  66. for (iter = mapS.begin(); iter != mapS.end(); iter ) {  
  67.   
  68. cout << "| " << iter->first << " | " << iter->   
  69. second << " |" << endl;  
  70.   
  71. }   
  72. cout << "=================================" << endl;  
  73.   
  74. return 0;   
  75. }  


本文参考:

http://blog.csdn.net/lyn_bigdream/article/details/6601510

http://blog.sina.com.cn/s/blog_63a1163f0100jxr9.html

http://wmnmtm.blog.163.com/blog/static/38245714201072310131130/
原创粉丝点击