map vector

我常用的STL(标准模板库) vector,map:

vector:

#include <iostream>
#include <vector>
#include <map>
#include <algorithm> //包含着 std::Find()函数的实现
using namespace std;

#define MAX_SIZE 5
void main()
{

vector<int> vInt;//初始化一个整形的向量 初始都为空
vInt.clear();
for (int n = 0; n < MAX_SIZE; n++)
vInt.push_back(n);//在向量尾部依次插入0 到4
vector<int>::iterator itr = vInt.begin();//定义一个向量的迭代器 使它指向向量的头部
for (; itr != vInt.end();++itr)//向量的头部使有效值 而尾部不是有效值的,当迭代器没有指到尾部时 就一直的向下遍历
cout<<(*itr)<<endl;//输入迭代器所指的值,迭代器是类似于指针
vInt.pop_back();//在尾部删除一个元素
for (int n = 0; n < vInt.size(); n++)
cout<<vInt.at(n)<<endl;//.at()方法也是可以读取向量中的元素的
vector<int>::iterator itrFind = std::find(vInt.begin(),vInt.end(),2);//通过调用find函数找到指定值的迭代指针
if (itrFind != vInt.end())//判断是否找到了一个有效值
vInt.erase(itrFind);//用erase方法删除该迭代指针
for (int n = 0; n < vInt.size(); n++)
cout<<vInt[n]<<endl;//也可用[]去向量的值
vInt.resize(5,9);//将vInt的size扩展为5,新扩展的值初始为9,若5比原来的size小的话 那就保留前5个数值不变。
itr = vInt.begin();
for (; itr != vInt.end();++itr)
cout<<(*itr)<<endl;
cout<<vInt.size()<<endl;
vInt.assign(2,7);//将vInt的size设置为2 并初始化为7
itr = vInt.begin();
for (; itr != vInt.end();++itr)
cout<<(*itr)<<endl;
cout<<vInt.size()<<endl;
getchar();
}

map:

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

#define MAX_SIZE 5
void main()
{
map<int,string> mapStr;//创建map
mapStr[0] = "One";//用数组方式初始化
mapStr.insert(pair<int,string>(1,"Two"));//用insert pair值初始化
mapStr.insert(map<int,string>::value_type(2,"Three"));//用insert value_type初始化
map<int,string>::iterator itr = mapStr.begin(),itr_end = mapStr.end();//前序遍历
for (;itr!= itr_end;++itr)
cout<<(*itr).first <<" "<<(*itr).second.c_str()<<endl;

map<int,string>::reverse_iterator Ritr = mapStr.rbegin(),Ritr_end = mapStr.rend();//后续遍历
for (;Ritr!=Ritr_end;++Ritr)
cout<<(*Ritr).first <<" "<<(*Ritr).second.c_str()<<endl;
getchar();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值