11.1
map是关联式容器,元素式按关键字保存和访问的;
vector是顺序容器,其元素是按照它在容器中的位置来保存和访问的;
11.2
list:插入较多情况;
vector:动态数组;
deque:需要头部和尾部增删的情况;
map:字典;
set:添加忽略关键字;
11.3
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main() {
map<string, size_t> word_count;
string words;
while (cin>>words)
{
++word_count[words];
}
for (const auto &s : word_count)
cout << s.first << " occurs " << s.second << ((s.second > 1) ? " times " : " time ") << endl;
return 0;
}
11.4
#include<iostream>
#include<string>
#include<map>
#include<algorithm>
#include<set>
using namespace std;
int main() {
map<string, size_t> word_count;
set<string>exclude{
"you","i" };
string words;
while (cin>>words)
{
words.erase(find_if(words.begin(), words.end(), ::ispunct), words.end()); //删除单词后面的标点
for_each(words.begin(), words.end(), [](char& c) {
c = tolower(c); }); //单词转换为小写
if(exclude.find(words)==exclude.end()) //忽略部分单词
++word_count[words];
}
for (const auto &s : word_count)
cout << s.first << " occurs " << s.second << ((s.second > 1) ? " times " : " time ") << endl;
return 0;
}
11.5
set中只有关键字;
map包括关键字-值对;
11.6
set关联式容器,查找较快;
list顺序容器,查找关键字与容器的大小有关;
11.7
#include<iostream>
#include<string>
#include<map>
#include<vector>
using namespace std;
int main() {
map<string, vector<string>> family;
string first_name, last_name;
cin >> last_name;
while (cin >> first_name)
{
family[last_name].push_back(first_name);
}
for (const auto f : family) {
cout << f.first << endl;
for (const auto s : f.second)
cout << s << " ";
cout << endl;
}
return 0;
}
11.8
效率更高,不用遍历判断重复;
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {
vector<string>vs;
string s;
while (cin >>s)
{
if (find(vs.begin(), vs.end(), s) == vs.end())
vs.push_back(s);
}
for (const auto s : vs)
cout << s << " ";
cout << endl;
return 0;
}
11.9
map<string,list<size_t>> words_line;
11.10
对于有序容器必须定义元素的比较方法,默认<;
vector<int>::iterator 可以,因为定义了<;
list<int>::iterator不可以,未定义<;
11.11
#include <set>
#include