2015-06-27 80 views
0

我需要按字母顺序打印std::multimap,这两个作者姓名及其作品。按字母顺序打印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; 
} 

这打印出作者的名字,但不是他们的作品按字母顺序,我如何可以打印自己的作品按字母顺序以及任何想法。谢谢

+1

http://coliru.stacked-crooked.com/a/9b786a99a4f8778a – 0x499602D2

回答

4

将作品存放在有序容器中,如std::map<std::string, std::set<std::string>>

您还应该考虑如果您的程序被要求以各种其他语言的字母顺序打印时会发生什么情况的影响。像中国人。您的原始程序和我的解决方案都假设std :: string的operator<可以执行您所需的排序,但这不能保证非英语语言。

1

前面已经提出,只是使用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; 
} 

Demo