网投网站如何建设,建设工程施工合同无效,wordpress手动更新,门户网站app开发文章目录练习11.1练习11.2练习11.3练习11.4练习11.5练习11.6练习11.7练习11.8练习11.9练习11.10练习11.1 描述map 和 vector 的不同。 map 是关联容器#xff0c; vector 是顺序容器。
练习11.2 分别给出最适合使用 list、vector、deque、map以及set的例子。 list#xff1a…
文章目录练习11.1练习11.2练习11.3练习11.4练习11.5练习11.6练习11.7练习11.8练习11.9练习11.10练习11.1 描述map 和 vector 的不同。 map 是关联容器 vector 是顺序容器。
练习11.2 分别给出最适合使用 list、vector、deque、map以及set的例子。 list双向链表适合频繁插入删除元素的场景。vector适合频繁访问元素的场景。deque双端队列适合频繁在头尾插入删除元素的场景。map字典。set适合有序不重复的元素的场景。
练习11.3 编写你自己的单词计数程序。 #include iostream
#include map
#include string
#include algorithm
#include cctypeint main()
{std::mapstd::string, std::size_t word_count;std::string word;while (std::cin word)word_count[word];for (const auto elem : word_count)std::cout elem.first : elem.second \n;return 0;
}练习11.4 扩展你的程序忽略大小写和标点。例如“example.”、example,和Example应该递增相同的计数器。 #include iostream
#include map
#include string
#include algorithm
#include cctypevoid word_count_pro(std::mapstd::string, int m)
{std::string word;while (std::cin word){for (auto ch : word) ch tolower(ch);word.erase(std::remove_if(word.begin(), word.end(), ispunct),word.end());m[word];}for (const auto e : m) std::cout e.first : e.second \n;
}int main()
{std::mapstd::string, int m;word_count_pro(m);return 0;
}练习11.5 解释map和set的区别。你如何选择使用哪个 map 是键值对而 set 只有键没有值。当我需要存储键值对的时候使用 map而只需要键的时候使用 set。
练习11.6 解释set和list 的区别。你如何选择使用哪个 set 是有序不重复集合底层实现是红黑树而 list 是无序可重复集合底层实现是链表。
练习11.7 定义一个map关键字是家庭的姓值是一个vector保存家中孩子们的名。编写代码实现添加新的家庭以及向已有家庭中添加新的孩子。 mapstring, vectorstring m;
for (string ln; cout Last name:\n, cin ln ln ! q;)for (string cn; cout |-Childrens names:\n, cin cn cn ! q;)m[ln].push_back(cn);练习11.8 编写一个程序在一个vector而不是一个set中保存不重复的单词。使用set的优点是什么 #include iostream
#include string
#include vector
#include algorithmint main()
{std::vectorstd::string exclude { aa, bb, cc, dd, ee, ff };for (std::string word; std::cout Enter plz:\n, std::cin word;){auto is_excluded std::binary_search(exclude.cbegin(), exclude.cend(), word);auto reply is_excluded ? excluded : not excluded;std::cout reply std::endl;}return 0;
}set 的优点是集合本身的元素就是不重复。
练习11.9 定义一个map将单词与一个行号的list关联list中保存的是单词所出现的行号。 std::mapstd::string, std::liststd::size_t m;练习11.10 可以定义一个vector::iterator 到 int 的map吗list::iterator 到 int 的map呢对于两种情况如果不能解释为什么。 可以定义 vectorint::iterator 到 int 的map但是不能定义 listint::iterator 到 int 的map。因为map的键必须实现 操作list 的迭代器不支持比较运算。