第十一章 习题11-1-习题11-10

习题11-1

map是关联容器,可以存储两种类型不同的“键”-“值”对;

vector是顺序容器,只能存放单一数据类型;

关联容器中的元素是按关键字来保存和访问的;顺序容器中的元素是按他们在容器中的位置来顺序保存和访问的;

习题11-2

  1. list -- 需要在中间进行操作的情况。
  2. vector, 动态数组。
  3. deque -- 只需要在头尾进行操作的情况
  4. map -- 字典
  5. set -- 黑名单

习题11-3

    std::map<std::string, std::size_t> word_count;
    std::string word;
    while (std::cin >> word) ++word_count[word];

    for (const auto& w : word_count)
        std::cout << w.first << " : " << w.second << "\n";

习题11-4

参考书中P82页

需要注意的是,我输入的为data.txt文件,在文件中有中文字符标点符号?,程序报错:

Debug Assertion Failed!
Program:
..
Line: 36

Expression: c >= -1 && c <= 255

将中文符号去掉即可;


#include<iostream>  
#include<fstream>
#include<map> 
#include<string>
#include<algorithm>
#include<cctype>
using namespace std;

void main()
{
	fstream file("data.txt");
	map<string, size_t> word_count;
	string word;
	while (file >> word)
	{

		for (auto& ch : word) ch = tolower(ch);
		word.erase(remove_if(word.begin(), word.end(), ispunct), word.end());
		++word_count[word];
	}
	for (auto w : word_count)
		cout << w.first << "  " << w.second << endl;
}

习题11-5

map元素类型为pair,是一对值<key value>

set 元素类型只有一个值key;

如何选择视情况而定;

习题11-6

set中元素有序,且不可重复;

习题11-7

#include<iostream>  
#include<vector>
#include<map> 
#include<string>
#include<algorithm>
using namespace std;

void main()
{
	map<string, vector<string>> family = { {"li",{"bab"}},{"wang",{"ba"}} };
	family["li"].push_back( "mam");
	family["wang"].push_back("ma");
	for (auto &m : family)
	{
		cout << m.first << "  ";
		for (auto k : m.second)
		{
			cout << k << " ";
		}
		cout << endl;
	}


}

习题11-8

这一题是两个小问题,编程和回答问题;前后没有因果关系,不然题目有点读不懂。。。

set会自动忽略重复的词;vector插入操作比较耗时;


#include<iostream>  
#include<vector>
#include<string>
#include<algorithm>
using namespace std;

void main()
{
	vector<string> vec = { "sr","sa","sc","sa","sk","sr" ,"asc","akss","as"};
	for (auto &s : vec)
		cout << s << "  ";
	cout << endl;
	sort(vec.begin(), vec.end());
	auto end_unique = unique(vec.begin(), vec.end());
	vec.erase(end_unique, vec.end());
	for (auto &s : vec)
		cout << s << "  ";
	cout << endl;
}

习题11-9

map<string,list<int>>

习题11-10

vector可以,因为vector定义了比较大小,list没有定义大小比较;

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值