版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CV2017/article/details/85872465
注:看《C++ Primer 5》的笔记,不定期更新
map 是什么
map 是一种数据结构,是关键字-值对的集合,称为关联容器
map 实现单词计数程序
#include <iostream>
#include <map>
#include <string>
using namespace std;
void wordCound(map<string, size_t> word_count)
{
for (const auto &w : word_count)
{
cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl;
}
}
int main()
{
map<string, size_t> word_count;
string word;
while (cin >> word)
{
++word_count[word];
}
wordCound(word_count);
return 0;
}
提示:windows 平台下输入几个单词后,先按回车,再按 ctrl + z,再按回车
map 与 set 实现单词计数程序
#include <iostream>
#include <map>
#include <set>
#include <string>
using namespace std;
void wordCound(map<string, size_t> word_count)
{
for (const auto &w : word_count)
{
cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl;
}
}
int main()
{
map<string, size_t> word_count;
set<string> exclude = { "The", "But", "And", "Or" };
string word;
while (cin >> word)
{
if (exclude.find(word) == exclude.end())
{
++word_count[word];
}
}
wordCound(word_count);
return 0;
}
map 实现忽略大小写和标点的单词计数程序
#include <iostream>
#include <map>
#include <set>
#include <string>
using namespace std;
string& trans(string &s)
{
for (int p = 0; p < s.size(); p++)
{
if (s[p] >= 'A' && s[p] <= 'Z')
{
s[p] += 32;
}
else if (s[p] == ',' || s[p] == '.')
{
s.erase(p, 1);
}
}
return s;
}
void wordCound(map<string, size_t> word_count)
{
for (const auto &w : word_count)
{
cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl;
}
}
int main()
{
map<string, size_t> word_count;
set<string> exclude = { "The", "But", "And", "Or" };
string word;
while (cin >> word)
{
if (exclude.find(word) == exclude.end())
{
++word_count[trans(word)];
}
}
wordCound(word_count);
return 0;
}
map 含 vector 实现添加
#include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;
void addFamily(map<string, vector<string>> &families, const string &family)
{
if (families.find(family) == families.end())
{
families[family] = vector<string>(); //创建空的 vector
}
}
void addChild(map<string, vector<string>> &families, const string &family, const string &child)
{
families[family].push_back(child);
}
int main()
{
map<string, vector<string>> families;
addFamily(families, "王");
addChild(families, "王", "鑫");
addChild(families, "王", "一丁");
addFamily(families, "张");
for (auto f : families)
{
cout << f.first << " 家的孩子:";
for (auto c : f.second)
{
cout << c << " ";
}
cout << endl;
}
return 0;
}
map 与 vector 的区别
https://blog.csdn.net/CV2017/article/details/85222426
map 与 set 区别
map 是一对关键字-值的存储容器,set 是单个关键字即值的存储
map 适用场景
map 适合对一些对象按它们的某个特征进行访问,比如按学生的名字来查询学生信息,将学生名字作为关键字,学生信息作为元素值