Search code examples
c++stringvectorstd-pair

C++ display map that has vector


std::map<std::string, std::vector<string>> data;

In order to print out this by using copy, how should my std::ostream_iterator be?

Apparently std::ostream_iterator<std::pair<std::string, std::vector<std::string>>> out_it(std::cout, "\n"); did not make it.

My operator<< overload is the following std::ostream& operator<<(std::ostream& out, const std::pair<std::string, std::vector<std::string>>& p) and it writes out the p.first and p.second and returns it.


Solution

  • So here is a operator<< that will print out the contents of one pair from your map:

    std::ostream& operator<<(std::ostream& out, const std::pair<std::string, std::vector<std::string>>& p) {
        out << p.first << ": "; // prints the string from key
        for (const auto& i : p.second) // loops throught the whole vector that is asociated with that key
            out << i << ", ";
        return out;
    }
    

    So to use it in this example. If you ennter this into your map:

    std::map<std::string, std::vector<string>> data;
    std::vector<std::string> vec = {"VAL1", "VAL2", "VAL3"};
    data.insert(std::make_pair("KEY", vec));
    auto it = data.find("KEY");
    std::cout << *it;
    

    This would be what wil get printed out using the operator<< above:

    KEY: VAL1, VAL2, VAL3, 
    

    You can also change the formatting a bit so the comma isn't after the last value as well but that's only a cosmetic problem. Your problem was in that you wanted to print vector while it doesn't have std operator<<. So in order to print vector you must manually loop through it's content like in my example with the ranged for.