简体   繁体   English

C ++:如何将向量中包含的对象插入集合中?

[英]C++: How do I insert the objects contained in a vector into a set?

I have a vector of objects and I'm trying to copy each object into a set: 我有一个对象向量,我试图将每个对象复制到一个集合中:

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

This gives me an error that some kind of comparison (operator<' in '__x < __y'|) is missing from the call to insert. 这给我一个错误,即在插入调用中缺少某种比较('__x <__y'|中的operator <')。 I've tried 我试过了

minTreeOutputSet.insert(minTreeOutput[it]);

as well, but that this gives me the error that there is no match for operator[]. 同样,但这给了我一个错误,即操作符[]不匹配。

Is inserting objects into a set not allowed? 是否不允许将对象插入集合? How do I properly insert the objects in a vector into a set? 如何将向量中的对象正确插入集合中?

You say: 你说:

This gives me an error that some kind of comparison (operator<' in '__x < __y'|) is missing from the call to insert 这给我一个错误,即插入调用中缺少某种比较('__x <__y'|中的operator <')

Thus, you should define operator< for MinTreeEdge or pass in your own comparison callable type as the 2nd template argument for std::set<> . 因此,您应该为MinTreeEdge定义operator<或将您自己的比较可调用类型作为std::set<>的第二个模板参数传递。

Here is some sample code for both approaches: 这是这两种方法的一些示例代码:

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

I would suggest approach 1 unless you can't modify the definition of your type. 我建议采用方法1,除非您无法修改类型的定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM