Chapter 11.Associative Containers

本文探讨了关联容器与顺序容器在数据存储和检索方式上的根本不同,通过具体实例介绍了如何使用 C++ 中的 map 容器来实现基于键值的数据映射与转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关联容器和顺序容器有着根本的不同。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");
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值