【问题标题】:C++: How do I insert the objects contained in a vector into a set?C++:如何将向量中包含的对象插入到集合中?
【发布时间】:2016-08-21 04:48:38
【问题描述】:

我有一个对象向量,我正在尝试将每个对象复制到一个集合中:

std::set<MinTreeEdge>minTreeOutputSet;
for(std::vector<MinTreeEdge>::iterator it = minTreeOutput.begin(); it != minTreeOutput.begin(); ++it)
        minTreeOutputSet.insert(*it);

这给了我一个错误,即插入调用中缺少某种比较('__x

minTreeOutputSet.insert(minTreeOutput[it]);

也是如此,但这给了我一个错误,即 operator[] 不匹配。

不允许将对象插入集合吗?如何正确地将向量中的对象插入到集合中?

【问题讨论】:

  • 另外,您应该将itminTreeOutput.end() 进行比较,而不是begin()
  • 为您的MinTreeEdge 定义一个operator&lt;
  • 提示:那么你就可以做到std::set&lt;MinTreeEdge&gt; minTreeOutputSet{ minTreeOutput.begin(), minTreeOutput.end() };
  • 请发布minimal reproducible example,包括逐字错误消息!

标签: c++ vector stl insert set


【解决方案1】:

你说:

这给了我一个错误,某种比较(运算符

因此,您应该为MinTreeEdge 定义operator&lt;,或者传入您自己的比较可调用类型作为std::set&lt;&gt; 的第二个模板参数。

以下是这两种方法的一些示例代码:

#include <set>

struct A
{
    // approach 1: define operator< for your type
    bool operator<( A const& rhs ) const noexcept
    {
        return x < rhs.x;
    }

    int x;
};

struct B
{
    int x;
};

struct BCompare
{
    // approach 2: define a comparison callable
    bool operator()( B const& lhs, B const& rhs ) const noexcept
    {
        return lhs.x < rhs.x;
    };
};

int main()
{
    std::set<A> sa; // approach 1
    std::set<B, BCompare> sb; // approach 2
}

除非您无法修改类型的定义,否则我建议使用方法 1。

【讨论】:

  • 非常感谢,事实证明这两种方法都是必要的!
猜你喜欢
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-08
  • 2015-09-09
相关资源
最近更新 更多