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

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

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

#include

#include

#include

#include

#include

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 &transMap) {

map::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 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::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

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-09-26 00:36

浏览 743

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值