如何输出用作地图键的集合?

时间:2017-10-25 20:55:20

标签: c++

编译此代码时出现此错误:

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

错误来自标记为//HERE的行:

  

错误:无法将std::ostream {aka std::basic_ostream<char>}左值绑定到std::basic_ostream<char>&&

1 个答案:

答案 0 :(得分:5)

为密钥类型创建一个流运算符。

我个人不喜欢在std命名空间中创建重载,因此我创建了一个&#34;操纵器&#34;包装器:

<强> 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";
}

打印

{ 3 4 } -> 8