map关联容器类型通常理解为关联数组,由键(类型)和值(类型)组成。方便记忆以书店图书为例:map<ISBN,sale_item> bookstore;ISBN为键,对应图书sale_item为值,这使得我们能够通过键的顺序访问元素,而与元素在容器中的存储位置完全无关。
使用nap对象完成单词转换(C++ primer 第4版10.3.9),例:
<pre name="code" class="cpp">#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
using namespace std;
/*
* A program to transform words.
* Takes two arguments: The first is name of the word transformation file
* The second is name of the input to transform
*/
// opens in binding it to the given file
ifstream& open_file(ifstream &in, const string &file) // p256/p270
{
in.close(); // close in case it was already open
in.clear(); // clear any existing errors
// if the open fails, the stream will be in an invalid state
in.open(file.c_str()); // open the file we were given
return in; // condition state is good if open succeeded
}
int main(int argc, char **argv) // char *argv[] ?
{
// map to hold the world transformation pairs:
// key is the word to look for in the input; value is word to use in the output
map<string, string> trans_map;
string key, value;
if (argc != 3)
throw runtime_error("Wrong number of arguments");
// open transformation file and check that open succeeded
ifstream map_file;
if (!open_file(map_file, argv[1]))
throw runtime_error("no transformation file");
// read the transformation map and bulid the map
while (map_file >> key >> value)
trans_map.insert(make_pair(key, value));
// ok, now we're ready to do the transformations
// open the input file and check that the open succeeded
ifstream input;
if (!open_file(input, argv[2]))
throw runtime_error("no input file");
string line; // hold each line from the input
// read the text to transform it a line at a time
while (getline(input, line))//read the line from the input to the line
{
istringstream stream(line); // read the line a word at a time,bind to stream to the line we read
string word;
bool firstword = true; // controls whether a space is printed
while (stream >> word) //read a word from line
{
// ok: the actual mapwork, this part is the heart of the program
map<string, string>::const_iterator map_it = trans_map.find(word);
// if this word is in the transformation map
if (map_it != trans_map.end())
// replace it by the transformation value in the map
word = map_it->second;
if (firstword)
firstword = false;
else
cout << " "; // print space between words
cout << word;
}
cout << endl; // done with this line of input
}
return 0;
}
相关代码的解释如上图,值得注意的是:由于使用了ifstream和istringstream类,在头文件中需要包含<fstream><sstream>,on_file()函数为自定义函数,由于主函数
int main(int argc, char **argv)
在vs2010 debug报错,应该在cmd环境中输入指令(test test1.txt text2.txt)来执行程序,其中test为应用程序名,test1为单词转换表,test2为待转换的文本。
最终运行结果如下: