[英]C++: How do I insert the objects contained in a vector into a set?
我有一个对象向量,我试图将每个对象复制到一个集合中:
std::set<MinTreeEdge>minTreeOutputSet;
for(std::vector<MinTreeEdge>::iterator it = minTreeOutput.begin(); it != minTreeOutput.begin(); ++it)
minTreeOutputSet.insert(*it);
这给我一个错误,即在插入调用中缺少某种比较('__x <__y'|中的operator <')。 我试过了
minTreeOutputSet.insert(minTreeOutput[it]);
同样,但这给了我一个错误,即操作符[]不匹配。
是否不允许将对象插入集合? 如何将向量中的对象正确插入集合中?
你说:
这给我一个错误,即插入调用中缺少某种比较('__x <__y'|中的operator <')
因此,您应该为MinTreeEdge
定义operator<
或将您自己的比较可调用类型作为std::set<>
的第二个模板参数传递。
这是这两种方法的一些示例代码:
#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,除非您无法修改类型的定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.