练习11.1 描述map和vector的不同。
map的关键字可以是string类型 而vector只能按整型下标索引。
map有映射的作用,可存放更多数据。
练习11.2 分别给出最适合使用list vector deque map 以及set的例子。
list:排名作为下标查成绩,发现作弊者,从链表中删除。
vector :排名作为下标查对象,第一名湖人队,第二名凯尔特人队...
deque :排队,进一个出一个。
map; 以人名映射电话号码 地址。
set:将特定的某一类对象放一起,如世界500强企业的名字。
练习11.3 编写你自己的单词计数程序。
#include <iostream>
#include <string>
#include <map>
#include <set>
using namespace std;
int main()
{
map<string, size_t> word_count;
set<string> exclude{ "a","an","the","or","and" };
string word;
while (cin >> word) {
if (exclude.find(word) == exclude.cend()) {
++word_count[word];
}
}
for (auto i : word_count) {
cout << i.first << " occurs " << i.second << ((i.second > 1) ? " times" : " time" )<< endl;
}
return 0;
}
练习11.4 扩展你的程序,忽略大小写和标点。例如,“example.”、“example,”Example“应该递增相同的计数器。
#include <iostream>
#include <string>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
map<string, size_t> word_count;
set<string> exclude{ "a","an","the","or","and" };
string word;
while (cin >> word) {
// remove_if....这该死的算法在通用型迭代器中并没有真的删除元素
auto iter = remove_if(word.begin(), word.end(),ispunct);
word.erase(iter, word.end());
for (auto &s : word) {
s = tolower(s);
}
if (exclude.find(word) == exclude.cend()) {
++word_count[word];
}
}
for (auto i : word_count) {
cout << i.first << " occurs " << i.second << ((i.second > 1) ? " times" : " time") << endl;
}
return 0;
}