现在的位置: 首页 > 综合 > 正文

C++ STL Map使用

2018年02月06日 ⁄ 综合 ⁄ 共 1910字 ⁄ 字号 评论关闭

第一种:用insert函数插入pair数据

#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(){
	map<int,string> mapStudent;
 	mapStudent.insert(pair<int, string>(1,"student_one"));
  	mapStudent.insert(pair<int, string>(2,"student_two"));
   	mapStudent.insert(pair<int, string>(3,"student_three"));
    map<int, string>::iterator iter;
    for(iter=mapStudent.begin();iter!= mapStudent.end();iter++){
    	cout<<iter->first<<" "<<iter->second<<endl;
	}
	return 0;
}

第二种:用insert函数插入value_type数据

#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(){
	map<int,string> mapStudent;
 	mapStudent.insert(map<int, string>::value_type (1,"student_one"));
    mapStudent.insert(map<int, string>::value_type (2,"student_two"));
    mapStudent.insert(map<int, string>::value_type (3,"student_three"));
    map<int, string>::iterator iter;
    for(iter=mapStudent.begin();iter!= mapStudent.end();iter++){
    	cout<<iter->first<<" "<<iter->second<<endl;
	}
	return 0;
}

第三种:用数组方式插入数据

#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(){
	map<int,string> mapStudent;
 	mapStudent[1]="student_one";
  	mapStudent[2]="student_two";
    mapStudent[3]="student_three";
    map<int, string>::iterator iter;
    for(iter=mapStudent.begin();iter!= mapStudent.end();iter++){
    	cout<<iter->first<<" "<<iter->second<<endl;
	}
	return 0;
}

真正有用的是下面的根据关键字查找(字符串类型)其他信息

#include <map>
#include <string>
#include <iostream>
using namespace std;
int main(){
	map<string,string>mapStudent;
 	/*
 	mapStudent.insert(map<string, string>::value_type ("zhangsan","student_one"));
    mapStudent.insert(map<string, string>::value_type ("lisi","student_two"));
    mapStudent.insert(map<string, string>::value_type ("wangwu","student_three"));
	*/
	mapStudent["zhangsan"]="bad boy";
	mapStudent["lisi"]="good boy";
	mapStudent["wangwu"]="good girl";
    map<string,string>::iterator iter;
    iter=mapStudent.find("lisi");
    if(iter!=mapStudent.end()) cout<<iter->first<<":"<<iter->second<<endl;
    iter=mapStudent.find("tianqi");
    if(iter==mapStudent.end()) cout<<"There is no such a man"<<endl;
	return 0;
}

 

抱歉!评论已关闭.