关联容器和顺序容器有着根本的不同。Associative and sequential containers differ from one another in a fundamental way:Elements in an associative container are stored andretrieved by a key. In contrast,elements in a sequential container are stored and accessed sequentially by their position in the container.
retrieve data 检索数据 retrieve 取回 检索 挽回
练习11.33:
#include <iostream>
#include <map>
#include <string>
#include <fstream>//file stream
#include <sstream>
using std::string;
using std::ifstream;
std::map<string, string> buildMap(ifstream& map_file)
{
std::map<string, string> trans_map;
for (string key, value; map_file >> key && getline(map_file, value);)
if (value.size() > 1)
trans_map[key] =value.substr(1).substr(0, value.find_last_not_of(' '));
return trans_map;
}
const string& transform(const string& s, const std::map<string, string>& m)
{
auto map_it = m.find(s);
return map_it == m.cend() ? s : map_it->second;
}
void word_transform(ifstream& map, ifstream& input)//ifstream(input file stream)//ofstream(output file stream)
{
auto trans_map = buildMap(map);
for (string text; getline(input, text);)
{
std::istringstream iss(text);
for (string word; iss >> word;)
std::cout << transform(word, trans_map) << " ";
std::cout << std::endl;
}
}
int main()
{
ifstream ifs_map("C:/Users/Administrator/Desktop/given_to_transform.txt"),
ifs_content("C:/Users/Administrator/Desktop/word_transformation_bad.txt");
if (ifs_map && ifs_content)
word_transform(ifs_map, ifs_content);
else
std::cerr << "can't find the documents." << std::endl;
system("pause");
}