64,666
社区成员
发帖
与我相关
我的任务
分享
//---------------------------------------------------------------------------
/*//-----------------------------------------------------------------------
一、Map 相应操作的范例以及解释
1:赋值操作
2、遍历操作
3、查找操作
4、改变对应value值操作
5、pair、vector与map的结合
/*///-----------------------------------------------------------------------
#include <vcl.h>
#include <map>
#include <bitset>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
#pragma hdrstop
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
map<int, string> mapStudent;
mapStudent.insert(pair<int, string>(2, "student_2"));
mapStudent.insert(pair<int, string>(3, "student_3"));
mapStudent.insert(pair<int, string>(1, "student_1"));
//*********一、Map 输出指定值 方法 1
cout<<endl<<"输出指定值 方法 1-替换输出 "<<endl;
map<int, string>::iterator iter; //获取指向,防止直接调用map时改变值
iter = mapStudent.find(2);
if(iter != mapStudent.end()) {
cout<<"Find, the value is "<<iter->second<<endl; //method 1
}
else {
cout<<"Do not Find"<<endl;
}
//*********Map 输出指定值 方法 2
cout<<"输出指定值 方法 2-直接输出 "<<endl;
cout<<"Find, the value is "<<mapStudent.find(3)->second<<endl; //直接输出
//******依次遍历输出 默认遍历序是根据key升序排列的。 注意,此时已经按键值排好序了。不再需要重新排序
cout<<endl<<"依次遍历输出"<<endl;
for (map<int, string>::iterator it = mapStudent.begin(); it != mapStudent.end(); ++it) {
// it->first 是 key, it->second 是 value,遍历顺序是按key升序。
cout << it->first << ":" << it->second << endl;
}
//*********Map 改变某键值对应的value
cout<<endl<<"改变指定key的value"<<endl;
map<int, string>::iterator iter1; //获取指向,防止直接调用map时改变值
iter1 = mapStudent.find(2); //改变key=2 的value
if(iter1 != mapStudent.end()) {
cout<<"the initial value is "<<iter1->second<<endl; //改变前
iter1->second+=" add something";//改变对应的value
cout<<"the new value is :"<<iter1->second<<endl; //改变后
}
else {
cout<<"Do not Find"<<endl;
}
//***********Map vector 和 map结合
cout<<endl<<"vector 和 map结合 "<<endl;
map<int, vector<int> > mapVector;
vector <int> Number;
Number.push_back(11); //往vector 里面写入数据
Number.push_back(21);
Number.push_back(31);
mapVector.insert(pair<int, vector<int> >(2, Number)); //最终目的:map[0]={key=2,value=11,21,31}
cout<<"遍历输出指定key=2的value(vetor)的值: "<<endl;
int Tsize=mapVector.find(2)->second.size(); //先获取边界,避免每次循环都计算边界
for(int j=0;j<Tsize;j++ ) //遍历输出
cout<<j<<" value is "<<mapVector.find(2)->second[j]<<endl;
//***Map 指定key的 改变vector的值
cout<<endl<<"vector 和 map结合:改变指定key 的value(vector)值 "<<endl;
mapVector.find(2)->second.push_back(41); //尾后加41值
Tsize=mapVector.find(2)->second.size();//先获取边界,避免每次循环都计算边界
for(int j=0;j<Tsize;j++ ) //遍历输出
cout<<j<<" value is "<<mapVector.find(2)->second[j]<<endl;
cout<<" value is "<<sizeof(mapVector)<<endl;
system("pause");
}