Itolet Itolet - 3 months ago 9
C++ Question

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. 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?

Answer

You say:

This gives me an error that some kind of comparison (operator<' in '__x < __y'|) is missing from the call to insert

Thus, you should define operator< for MinTreeEdge or pass in your own comparison callable type as the 2nd template argument for 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.

Comments