按字母顺序打印 std::multimap 个键和值
Print std::multimap keys and values alphabetically
我需要按字母顺序打印 std::multimap
,包括作者姓名和他们的作品。
#include <string>
#include <map>
int main()
{
std::multimap<std::string, std::string> authors = {{"Captain", "Nothing"}, {"ChajusSaib", "Foo"},
{"ChajusSaib", "Blah"}, {"Captain", "Everything"}, {"ChajusSaib", "Cat"}};
for (const auto &b : authors)
{
std::cout << "Author:\t" << b.first << "\nBook:\t\t" << b.second << std::endl;
}
return 0;
}
这会打印出作者的姓名,但不会按字母顺序打印出他们的作品,关于我如何也可以按字母顺序打印他们的作品的任何想法。谢谢
将作品存放在有序的容器中,例如std::map<std::string, std::set<std::string>>
。
您还应该考虑如果要求您的程序按字母顺序打印各种其他语言时发生的情况的影响。喜欢中国人。您的原始程序和我的解决方案都假设 std::string 的 operator<
可以执行您需要的排序,但这不能保证非英语语言。
如前所述,只需使用 std::set
作为映射类型:
std::multimap<std::string, std::set<std::string>> authors = {{"Captain", {"Nothing", "Everything"}},
{"ChajusSaib", {"Foo", "Blah", "Cat"}}};
for (auto const &auth : authors) {
std::cout << "Author: " << auth.first << std::endl;
std::cout << "Books:" << std::endl;
for (auto const &book: auth.second)
std::cout << "\t" << book << std::endl;
std::cout << std::endl;
}
我需要按字母顺序打印 std::multimap
,包括作者姓名和他们的作品。
#include <string>
#include <map>
int main()
{
std::multimap<std::string, std::string> authors = {{"Captain", "Nothing"}, {"ChajusSaib", "Foo"},
{"ChajusSaib", "Blah"}, {"Captain", "Everything"}, {"ChajusSaib", "Cat"}};
for (const auto &b : authors)
{
std::cout << "Author:\t" << b.first << "\nBook:\t\t" << b.second << std::endl;
}
return 0;
}
这会打印出作者的姓名,但不会按字母顺序打印出他们的作品,关于我如何也可以按字母顺序打印他们的作品的任何想法。谢谢
将作品存放在有序的容器中,例如std::map<std::string, std::set<std::string>>
。
您还应该考虑如果要求您的程序按字母顺序打印各种其他语言时发生的情况的影响。喜欢中国人。您的原始程序和我的解决方案都假设 std::string 的 operator<
可以执行您需要的排序,但这不能保证非英语语言。
如前所述,只需使用 std::set
作为映射类型:
std::multimap<std::string, std::set<std::string>> authors = {{"Captain", {"Nothing", "Everything"}},
{"ChajusSaib", {"Foo", "Blah", "Cat"}}};
for (auto const &auth : authors) {
std::cout << "Author: " << auth.first << std::endl;
std::cout << "Books:" << std::endl;
for (auto const &book: auth.second)
std::cout << "\t" << book << std::endl;
std::cout << std::endl;
}