标准STL中的关联容器有:set、multiset、map、multimap
其中map用于存放关联数组(键值对),set是存放不同键值的集合,和multimap、multiset的
差别就是map、set中key_value只能对应唯一的mapped_type,而multi类型则可以有多个
对应关系。
其中有两个例子用来表示map的用法,一个是单词词数统计,一个是单词转换:
/*
* 单词统计测试
*/
#include <iostream>
#include <sstream>
#include <string>
#include <map>
using namespace std;
int main(void)
{
string line,word;
map<string,int> word_cout;
cout<<"Please input a line word:"<<endl;
if(!getline(cin,line))
throw runtime_error("getline error!");
istringstream stream(line);
while (stream>>word)
{
pair<map<string,int>::iterator,bool> ret=
word_cout.insert(make_pair(word,1));
if (!ret.second)
{
++ret.first->second;
}
}
map<string,int>::const_iterator map_iter=word_cout.begin();
cout<<"word\ttimes"<<endl;
while (map_iter!=word_cout.end())
{
cout<<map_iter->first<<"\t"<<map_iter->second<<endl;
++map_iter;
}
return 0;
}
/*
* 单词转换
*/
#include <map>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;
ifstream &open_file(ifstream &in,const string &file)
{
in.close();
in.clear();
in.open(file.c_str());
return in;
}
int main(void)
{
// if (argc!=3)
// {
// throw runtime_error("wrong number arguments!");
// }
map<string,string> trans_map;
string key,val;
ifstream map_file;
open_file(map_file,string("trans.txt"));
while (map_file>>key>>val)
{
trans_map.insert(make_pair(key,val));
}
ifstream input;
if(!open_file(input,string("input.txt")))
throw runtime_error("no input file ");
string line;
while (getline(input,line))
{
istringstream stream(line);
string word;
bool firstword=true;
while (stream>>word)
{
map<string,string>::const_iterator map_it=
trans_map.find(word);
if (map_it!=trans_map.end())
{
word=map_it->second;
}
if (firstword)
{
firstword=false;
}
else
cout<<" ";
cout<<word;
}
cout<<endl;
}
return 0;
}