习题11-1
map是关联容器,可以存储两种类型不同的“键”-“值”对;
vector是顺序容器,只能存放单一数据类型;
关联容器中的元素是按关键字来保存和访问的;顺序容器中的元素是按他们在容器中的位置来顺序保存和访问的;
习题11-2
- list -- 需要在中间进行操作的情况。
- vector, 动态数组。
- deque -- 只需要在头尾进行操作的情况
- map -- 字典
- 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没有定义大小比较;