您的位置:首页 > 编程语言 > C语言/C++

c++学习笔记-map的使用实例(单词转换)

2012-09-26 00:36 543 查看
c++中的map是关联容器,以key-value的形式存储数据,类似于java中的Map类型和python中的dict。key不能重复,并能通过下标的形式(map[key])返回value,因此也被称为关联数组。注意:使用下标的形式赋值时会多一次初始化的操作,举个例子:map<string,int>,map["alex"] = 1,首先会检查alex这个key是否存在,如果存在则更新key对应的值为1,如果不存在则插入一个key,然后初始化其对应的value为0,最后更新其value为1.

下面根据一个简单的单词转换程序来学习map遍历、插入、删除、更新元素的操作。

#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <string>

using namespace std;

//打开文件
ifstream& open_file(ifstream &in,const string &file) {
in.close();
in.clear();
in.open(file.c_str());
return in;
}

//遍历map
void traversalMap(const map<string,string> &transMap) {
map<string,string>::const_iterator tempMapIt = transMap.begin();
while(tempMapIt != transMap.end()) {
cout << tempMapIt->first << "--" << tempMapIt->second << endl;
++ tempMapIt;
}
cout << "*****************************************" << endl;
}
int main(int argc,char **argv) {
if(argc != 3)
throw runtime_error("arguments error");
map<string,string> transMap;
string key,value;
ifstream mapFile;
if(!open_file(mapFile,argv[1]))
throw runtime_error("open file error");
//插入数据
while(mapFile >> key >> value) {
transMap.insert(make_pair(key,value));
}
traversalMap(transMap);

ifstream input;
if(!open_file(input,argv[2]))
throw runtime_error("open file error");
string line;
//读取一行字符串
while(getline(input,line)) {
istringstream stream(line);
string word;
bool firstWorld = true;

//从一行字符串中读取一个单词
while(stream >> word) {
//查找word是否存在于map中
map<string,string>::const_iterator mapIt = transMap.find(word);
if(mapIt != transMap.end())
word = mapIt->second;
if(firstWorld)
firstWorld = false;
else
cout << " ";
cout << word;
}
cout << endl;
}
//更新key=f的值
transMap["f"] = "alexzhou";
traversalMap(transMap);
//删除key=f对应的元素
transMap.erase("f");
traversalMap(transMap);
//给key=f赋值,此时key不存在
transMap["f"] = "world";
traversalMap(transMap);

return 0;
}


这个程序我是在vs2010里运行的,需要设置一下运行时的参数,在项目属性里面 配置属性-》调试-》命令参数 里面写上你的参数,如:e:\\map.txt e:\\input.txt 。或者在cmd执行该项目生成的exe文件:StudyMap.exe e:\\map.txt e:\\input.txt

map.txt的文件内容为:

a my

b name

c is

d alexzhou

e hello

f world

input.txt文件的内容:

a b c d

e f

转载请注明来自:Alex Zhou,本文链接:http://codingnow.cn/c-c/619.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: