【问题标题】:How do I output a set used as key for a map?如何输出用作地图键的集合?
【发布时间】:2017-11-03 06:47:49
【问题描述】:

编译这段代码时出现这个错误:

#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&lt;char&gt;} 左值绑定到 std::basic_ostream&lt;char&gt;&amp;&amp;

【问题讨论】:

  • 你的map的key类型是set!?不应该反过来吗?
  • 应该是数组、向量或集合
  • it-&gt;firststd::set&lt;int&gt;,并且没有流插入运算符。我没有解决方案,因为我不知道您要完成什么。
  • 那我能做什么?
  • 我在集合中有一些整数,或者它可以在数组或向量中,我想将其中一些映射到零,而将其中一些映射到 1

标签: c++


【解决方案1】:

为键类型创建一个流操作符。

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

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

【讨论】:

  • 除了不喜欢之外,这是undefined behavior这样做!
  • 对我来说非常复杂
  • 是c++,恐怕不会变得不那么复杂。
  • 以下内容可能有助于您理解代码:in imperative fashion。它导致更少的通用和更少的惯用 C++。值得注意的是,现在它不能同时用于set&lt;int&gt;vector&lt;int&gt;,但也许你更喜欢它?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
  • 2016-08-24
  • 2018-05-12
相关资源
最近更新 更多