C++STL Map使用


1つ目: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;
}

2つ目: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;
}

3つ目:配列でデータを挿入する
#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;
}