练习11.1:
map是关联容器,元素是一些关键字-值对,关键字起到索引作用,类似vector中的位置(下标),通过关键字对值进行操作
vector是顺序容器,在vector中元素是按顺序存储的,每个元素都对应一个位置,通过这个位置能对元素进行操作
练习11.2:
vector:有很多随机访问元素操作,一般在尾部插入元素
list:大多是顺序访问操作,频繁在list中插入元素
deque:有很多随机访问元素操作,有在首位置插入元素的需求
map:使用于通过姓名查找电话号码的操作
set:需要排除一些满足或不满足某些值的操作
练习11.3:
#include <iostream>
using namespace std;
#include <map>
#include <string>
#include <set>
int main()
{
map<string, size_t>word_count;
string word;
int i = 10;
//输入十对单词-计数器对
while (i != 0 && cin >> word)
{
++word_count[word];
--i;
}
for (const auto& w : word_count)
{
cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times " : " time") << endl;
}
system("pause");
return 0;
}
练习11.4:对于每个从标准输入读取的单词,删除其标点,并将大写变为小写,这里标点符号我们就以书上给的两个为例',','.'。
#include <iostream>
using namespace std;
#include <map>
#include <string>
#include <set>
int main()
{
map<string, size_t>word_count;
string word;
int i = 10;
//输入十对单词-计数器对
while (i != 0 && cin >> word)
{
//删除标点,并将大写变为小写
for (size_t i = 0; i < word.size(); ++i)
{
//大写变小写
if ('A' <= word[i] <= 'Z')
{
word[i] = tolower(word[i]);
}
//去除标点,也可以增加其他标点,这里只举例了两个标点
if (word[i] == ',' || word[i] == '.')
{
//删除容器中从i位置开始的1个元素。返回值是经过删除操作后的容器
word = word.erase(i, 1);
//更新i,继续向后检测
i -= 1;
}
}
++word_count[word];
--i;
}
for (const auto& w : word_count)
{
cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times " : " time") << endl;
}
system("pause");
return 0;
}