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

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中重复的元素

#include <iostream>
#include <list>
#include <numeric>
#include <algorithm>

using namespace std;

//创建一个list容器的实例LISTINT
typedef list<int> LISTINT;

//创建一个list容器的实例LISTCHAR
typedef list<char> LISTCHAR;

int main(void)
{
    //--------------------------
    //用list容器处理整型数据
    //--------------------------
    //用LISTINT创建一个名为listOne的list对象
    LISTINT listOne;
    //声明i为迭代器
    LISTINT::iterator i;

    //从前面向listOne容器中添加数据
    listOne.push_front (2);
    listOne.push_front (1);

    //从后面向listOne容器中添加数据
    listOne.push_back (3);
    listOne.push_back (4);

    //从前向后显示listOne中的数据
    cout<<"listOne.begin()--- listOne.end():"<<endl;
    for (i = listOne.begin(); i != listOne.end(); ++i)
        cout << *i << " ";
    cout << endl;

    //从后向后显示listOne中的数据
    LISTINT::reverse_iterator ir;
    cout<<"listOne.rbegin()---listOne.rend():"<<endl;
    for (ir =listOne.rbegin(); ir!=listOne.rend();ir++) {
        cout << *ir << " ";
    }
    cout << endl;

    //使用STL的accumulate(累加)算法
    int result = accumulate(listOne.begin(), listOne.end(),0);
    cout<<"Sum="<<result<<endl;
    cout<<"------------------"<<endl;

    //--------------------------
    //用list容器处理字符型数据
    //--------------------------

    //用LISTCHAR创建一个名为listOne的list对象
    LISTCHAR listTwo;
    //声明i为迭代器
    LISTCHAR::iterator j;

    //从前面向listTwo容器中添加数据
    listTwo.push_front ('A');
    listTwo.push_front ('B');

    //从后面向listTwo容器中添加数据
    listTwo.push_back ('x');
    listTwo.push_back ('y');

    //从前向后显示listTwo中的数据
    cout<<"listTwo.begin()---listTwo.end():"<<endl;
    for (j = listTwo.begin(); j != listTwo.end(); ++j)
        cout << char(*j) << " ";
    cout << endl;

    //使用STL的max_element算法求listTwo中的最大元素并显示
    j=max_element(listTwo.begin(),listTwo.end());
    cout << "The maximum element in listTwo is: "<<char(*j)<<endl;

    return 0;
}
2.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附带函数
 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交换数据

 vector 的数据的存入和输出:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
 
int main(void)
{
   vector<int> num;   // STL中的vector容器
   int element;
 
   // 从标准输入设备读入整数, 
   // 直到输入的是非整型数据为止
   while (cin >> element)     //ctrl+Z 结束输入 
      num.push_back(element);
 
   // STL中的排序算法
   sort(vi.begin() , vi.end()); /// 从小到大  
   reverse(vi.begin(),vi.end()) /// 从大道小 
 
 
   // 将排序结果输出到标准输出设备
   for (int i = 0; i < num.size(); i ++)
      cout << num[i] << "\n";
   //也可以这样做
   
      
   system("pause");
   return 0;
}
对于二维vector的定义

1)定义一个10个vector元素,并对每个vector符值1-10。

#include<stdio.h>
#include<vector>
#include <iostream>
using namespace std;
int main()
{
 int i = 0, j = 0;
//定义一个二维的动态数组,有10行,每一行是一个用一个vector存储这一行的数据。
所 以每一行的长度是可以变化的。之所以用到vector<int>(0)是对vector初始化,否则不能对vector存入元素。
 vector< vector<int> > Array( 10, vector<int>(0) ); 
for( j = 0; j < 10; j++ )
 {
  for ( i = 0; i < 9; i++ )
  {
   Array[ j ].push_back( i );
  }
 }
 for( j = 0; j < 10; j++ )
 {
  for( i = 0; i < Array[ j ].size(); i++ )
  {
   cout << Array[ j ][ i ] << "  ";
  }
  cout<< endl;
 }
}
定义一个行列都是变化的数组。

#include<stdio.h>
#include<vector>
#include <iostream>
using namespace std;
void main()
{
 int i = 0, j = 0;
 vector< vector<int> > Array;
 vector< int > line;
 for( j = 0; j < 10; j++ )
 {
  Array.push_back( line );//要对每一个vector初始化,否则不能存入元素。
  for ( i = 0; i < 9; i++ )
  {
   Array[ j ].push_back( i );
  }
 }
 for( j = 0; j < 10; j++ )
 {
  for( i = 0; i < Array[ j ].size(); i++ )
  {
   cout << Array[ j ][ i ] << "  ";
  }
  cout<< endl;
使 用 vettor erase 指定元素

#include <iostream>
#include <vector>

using namespace std;

int   main()
{
    vector<int>   arr;
    arr.push_back(6);
    arr.push_back(8);
    arr.push_back(3);
    arr.push_back(8);

    for(vector<int>::iterator it=arr.begin(); it!=arr.end(); )
    {
        if(* it == 8)
        {
            it = arr.erase(it);
        }
        else
        {
            ++it;
        }
    }

    cout << "After remove 8:\n";

    for(vector<int>::iterator it = arr.begin(); it < arr.end(); ++it)
    {
        cout << * it << " ";
    }
    cout << endl;
    return 0;
}

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的插入,查找,遍历及删除的例子:

#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.0.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; 
}

本文参考:

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/

http://blog.csdn.net/monkeyandy/article/details/7600043


转载于:https://my.oschina.net/gddyl/blog/113744

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值