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

来源:互联网 发布:c语言子程序调用实例 编辑:程序博客网 时间:2024/05/20 11:46

一:首先了解一下   什么是C++的迭代器Interator?  

       容器就是数据结构的泛指,迭代器就是指针的泛指,可以指向元素。容器相当于一个储藏柜,里面装的许多不同的物品就像是储存的元素,比如面包、啤酒、苹果、现金。要取得各个物体就得用与各个物体向匹配的工具,如取出面包要用盘子、取出啤酒要用杯子、取出苹果要用篮子、取出现金要用钱包。迭代器的作用就相当于取出物品的工具的抽象,通过迭代器泛指现实生活中从贮藏室中取出物体的工具C++迭代器是一种检查容器内元素并遍历元素的数据类型

1 Iterator definitions

In C++, an iterator is any object that, pointing to some element in a range of elements (such as an array or a container), has the ability to iterate through the elements of that range using a set of operators (at least, the increment (++) and dereference (*) operators).

The most obvious form of iterator is a pointer: A pointer can point to elements in an array, and can iterate through them using the increment operator (++). But other forms of iterators exist. For example, each container type (such as a vector) has a specific iterator type designed to iterate through its elements in an efficient way.

C++迭代器Interator就是一个指向某种STL对象的指针。通过该指针可以简单方便地遍历所有元素。 
C++中的iterator为STL中的重要概念。iterator的概念源自于对遍历一个线性容器工具的抽象,即如何你能访问这个容器的某个元素。对于最简单的数组,当然可以用数组的索引值,因为数组是连续存放在内存中的;但对于链表,就必须用指针。除此之外,还有还有很多种数据结构需要提供一个方便的工具来访问其中的元素,方法有ID,关键字等等。为了统一所有的容器的这种工具的使用,一般提供一整套容器的开发者就会用一种方式来表示各种容器的访问工具。例如C++   STL就是使用iterator。MFC自己的容器使用position。C#和java也有自己的方法,但方法是不变的。 
iterator的用法可以被统一,但不同的底层容器实现其iterator的原理是不一样的。例如iterator++你可以理解为移动到容器的下一个元素,如果底层如果是数组,把索引值加一就行;如果底层是链表,就得执行类似于m_pCurrent   =   m_pCurrent-> pNext;的操作。因此每种容器都有自己的iterator实现方法。
 
C++   STL   iterator的常用方法有: 
iterator++     移到下个元素 
iterator--     移到上个元素 
*iterator       访问iterator所指元素的值
  <   >   ==   !=     iterator之间的比较,例如判断哪个元素在前 
iterator1   +   iterator2     iterator之间的加法运算,类似于指针加法 

2 容器的 iterator 类型

每种容器类型都定义了自己的C++迭代器类型,如 vector:vector<int>::iterator iter;这符语句定义了一个名为 iter 的变量,它的数据类型是 vector<int> 定义的 iterator 类型。每个标准库容器类型都定义了一个名为 iterator 的成员,这里的 iterator 与迭代器实际类型的含义相同。

begin 和 end 操作每种容器都定义了一对命名为 begin 和 end 的函数,用于返回迭代器。如果容器中有元素的话,由 begin 返回的迭代器指向第一个元素:

                                     vector<int>::iterator iter = ivec.begin();

上述语句把 iter 初始化为由名为 vector 操作返回的值。假设 vector 不空,初始化后,iter 即指该元素为ivec[0]。

由 end 操作返回的C++迭代器指向 vector 的“末端元素的下一个”。“超出末端迭代器”(off-the-end iterator)。表明它指向了一个不存在的元素。如果 vector 为空,begin 返回的迭代器与 end 返回的迭代器相同。由 end 操作返回的迭代器并不指向 vector 中任何实际的元素,相反,它只是起一个哨兵(sentinel)的作用,表示我们已处理完 vector 中所有元素。

a)使用迭代器读取vector中的每一个元素
vector<int> ivec(10,1);
for(vector<int>::iterator iter=ivec.begin();iter!=ivec.end();++iter)
{
       *iter=2; //使用 * 访问迭代器所指向的元素
}


b)const_iterator只能读取容器中的元素,而不能修改
for(vector<int>::const_iterator citer=ivec.begin();citer!=ivec.end();citer++)
{
         cout<<*citer;
         //*citer=3; error
}

3 vector 迭代器的自增和解引用运算

C++迭代器类型定义了一些操作来获取迭代器所指向的元素,并允许程序员将迭代器从一个元素移动到另一个元素。迭代器类型可使用解引用操作符(dereference operator)(*)来访问迭代器所指向的元素:

                 *iter = 0;

解引用操作符返回迭代器当前所指向的元素。假设 iter 指向 vector 对象 ivec 的第一元素,那么 *iter 和ivec[0] 就是指向同一个元素。上面这个语句的效果就是把这个元素的值赋为 0。迭代器使用自增操作符向前移动迭代器指向容器中下一个元素。从逻辑上说,C++迭代器的自增操作和int 型对象的自增操作类似。对 int 对象来说,操作结果就是把 int 型值“加 1”,而对迭代器对象则是把容器中的迭代器“向前移动一个位置”。因此,如果 iter 指向第一个元素,则 ++iter 指向第二个元素。由于 end 操作返回的迭代器不指向任何元素,因此不能对它进行解引用或自增操作。

二: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. }  


output:


listOne.begin()--- listOne.end():1 2 3 4 listOne.rbegin()---listOne.rend():4 3 2 1 Sum=10------------------listTwo.begin()---listTwo.end():B A x y The maximum element in listTwo is: y


三: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
  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. }  

output:

After remove 8:6 3


附:

 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>   
    #include <string>   
    #include <iostream>   
    using namespace std;  
      
    void map_insert(map < string, string > *mapStudent, string index, string x)   
    {   
    mapStudent->insert(map < string, string >::value_type(index, x));   
    }  
      
    int main(int argc, char **argv)   
    {   
    char tmp[32] = "";   
    map < string, string > mapS;  
      
    //insert element   
    map_insert(&mapS, "192.168.0.128", "xiong");   
    map_insert(&mapS, "192.168.200.3", "feng");   
    map_insert(&mapS, "192.168.200.33", "xiongfeng");  
      
    map < string, string >::iterator iter;  
      
    cout << "We Have Third Element:" << endl;   
    cout << "-----------------------------" << endl;  
      
    //find element   
    iter = mapS.find("192.168.200.33");   
    if (iter != mapS.end()) {   
    cout << "find the elememt" << endl;   
    cout << "It is:" << iter->second << endl;   
    } else {   
    cout << "not find the element" << endl;   
    }  
      
    //see element   
    for (iter = mapS.begin(); iter != mapS.end(); iter++ ) {  
      
    cout << "| " << iter->first << " | " << iter->   
    second << " |" << endl;  
      
    }   
    cout << "-----------------------------" << endl;  
      
    map_insert(&mapS, "192.168.30.23", "xf");  
      
    cout << "After We Insert One Element:" << endl;   
    cout << "-----------------------------" << endl;   
    for (iter = mapS.begin(); iter != mapS.end(); iter++ ) {  
      
    cout << "| " << iter->first << " | " << iter->   
    second << " |" << endl;   
    }  
      
    cout << "-----------------------------" << endl;  
      
    //delete element   
    iter = mapS.find("192.168.200.33");   
    if (iter != mapS.end()) {   
    cout << "find the element:" << iter->first << endl;   
    cout << "delete element:" << iter->first << endl;   
    cout << "=================================" << endl;   
    mapS.erase(iter);   
    } else {   
    cout << "not find the element" << endl;   
    }   
    for (iter = mapS.begin(); iter != mapS.end(); iter ++) {  
      
    cout << "| " << iter->first << " | " << iter->   
    second << " |" << endl;  
      
    }   
    cout << "=================================" << endl;  
      
    return 0;   
    }  

output:


We Have Third Element:-----------------------------find the elememtIt is:xiongfeng| 192.168.0.128 | xiong || 192.168.200.3 | feng || 192.168.200.33 | xiongfeng |-----------------------------After We Insert One Element:-----------------------------| 192.168.0.128 | xiong || 192.168.200.3 | feng || 192.168.200.33 | xiongfeng || 192.168.30.23 | xf |-----------------------------find the element:192.168.200.33delete element:192.168.200.33=================================| 192.168.0.128 | xiong || 192.168.200.3 | feng || 192.168.30.23 | xf |=================================


本文参考:

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/

0 0