11.1
map是一种关联容器
vector是一种顺序容器
顺序容器强调值的排序,而关联式容器则在值中选择一个值作为一个关键字,这个关键字起到对值的索引的作用,方便查找。
11.2
list适合需要频繁插入删除的容器
vector适合一般情况
deque适合在两端的操作
map适合关键字-值的操作
set则是关键字就是值
11.3
Map count() {
Map counts;
std::string word;
while (std::cin >> word) {
++counts[word];
}
return counts;
}
11.4
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <cctype>
using std::string;
using std::cin;
using std::cout;
using std::remove_if;
using Map = std::map<std::string, std::size_t>;
Map count() {
Map counts;
std::string word;
while (std::cin >> word) {
++counts[word];
}
return counts;
}
auto strip(string& str) -> string const&
{
for (auto& ch : str) ch = tolower(ch);
str.erase(remove_if(str.begin(), str.end(), ispunct), str.end());
return str;
}
auto strip_and_count()
{
Map counts;
for (string w; cin >> w; ++counts[strip(w)]);
return counts;
}
auto print(Map const& m)
{
for (auto const& kv : m)
cout << kv.first << " : " << kv.second << "\n";
}
int main()
{
cout << "cin:\n";
print(count());
cin.clear();
cout << "cin:\n";
print(strip_and_count());
return 0;
}