Search code examples
c++c++11c++14multimap

Print std::multimap keys and values alphabetically


I need to print out std::multimap alphabetically, both the authors names and their works.

#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;   
}

This prints out the authors names but not their works alphabetically, any idea on how I could print their works alphabetically as well. Thanks


Solution

  • Store the works in an ordered container, like std::map<std::string, std::set<std::string>>.

    You should also consider the impact of what happens if your program is called upon to print in alphabetical order for various other languages. Like Chinese. Both your original program and my solution make an assumption that std::string's operator< can perform the ordering you need, but this is no guarantee for non-English languages.