How to display the set used as a key for a card?

I get this error when compiling this code:

#include <map>
#include <set>
#include <iostream>

int main() {
    using std::set;
    using std::map;

    set<int> s;
    s.insert(4);
    s.insert(3);

    map<set<int>, int> myMap;

    myMap.insert(make_pair(s, 8));

    for (map<set<int>, int>::iterator it = myMap.begin(); it != myMap.end();
            it++) {

        std::cout << it->first << "->" << it->second << std::endl; // HERE
    }
    return 0;
}

The error is indicated on the line //HERE:

error: cannot bind std::ostream{aka std:: basic_ostream <char> } lvalue tostd::basic_ostream<char>&&

+4
source share
1 answer

Make a stream statement for the key type.

I personally don’t like creating overloads in the namespace std, so I create a “manipulator” shell:

Live On Coliru

#include <set>
#include <map>
#include <iostream>
#include <iterator>

template <typename T>
struct io {
    io(T const& t) : t(t) {}
  private:
    T const& t;

    friend std::ostream& operator<<(std::ostream& os, io const& o) {
        os << "{ ";
        using namespace std;
        copy(begin(o.t), end(o.t), ostream_iterator<typename T::value_type>(os, " "));
        return os << "}";
    }
};

int main() {  
    using namespace std;
    auto myMap = map<set<int>, int> { { { { 4, 3 }, 8 } } };

    for (auto& [k,v] : myMap)
        std::cout << io{k} << " -> " << v << "\n";
}

Print

{ 3 4 } -> 8
+5
source

Source: https://habr.com/ru/post/1688186/


All Articles