2015-06-27 44 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