c ++集合容器的问题 [英] problems with c++ set container
问题描述
当我尝试编译以下代码时:
When I try to compile the following code:
#include <iostream>
#include <set>
#include <vector>
using namespace std;
template <class T, class S>
class Property
{
public:
pair<T,S> p;
Property(T t, S s) { p = make_pair(t,s);}
};
int main()
{
set< Property<string, string> > properties;
Property<string, string> name("name", "Andy");
properties.insert(name);
}
我得到编译错误。
然而,当我替换set通过向量,因此使用push_back函数,而不是插入函数一切正常。谁能解释我我做错了什么?
感谢您的建议。
I get the compilation error. However, when I replace set by vector and hence use the the push_back function instead of insert function everything works fine. Could anyone explain me what am I doing wrong? Thanks in advice.
推荐答案
std :: set
将其值存储在排序的二叉树中,因此需要知道如何比较它保存的值。默认情况下,它使用 std :: less
作为比较函数,对于非专用的用户定义类型,尝试调用 operator
运算符<
:
template <class T, class S>
class Property
{
public:
pair<T,S> p;
Property(T t, S s) { p = make_pair(t,s);}
bool operator<(const Property<T,S>& rhs) const
{
return p < rhs.p;
}
};
但是,还有其他方法可以告诉 std :: set
如何比较你的类型。一个是为您的类专门化
std :: less
模板:
However, there are also other ways of telling std::set
how to compare your type. One is to specialize the std::less
template for your class:
namespace std {
template<typename T,typename S>
struct less<Property<T, S> >
{
bool operator()(const Property<T, S>& lhs, const Property<T,S>& rhs) const
{
return lhs.p < rhs.p;
}
};
}
<或具有使用正确签名定义的运算符()
的类。这是事情开始变得丑陋的地方。
Another is to replace the default comparison type with a function with the correct signature, or a class that has an operator()
defined with the correct signature. This is where things start to get ugly.
// Comparison function
template<typename T, typename S>
bool property_less_function(const Property<T,S>& lhs, const Property<T,S>& rhs)
{
return lhs.p < rhs.p;
}
// Comparison functor
template<typename T, typename S>
struct PropertyLess
{
bool operator()(const Property<T,S>& lhs, const Property<T,S>& rhs) const
{
return lhs.p < rhs.p;
}
};
int main()
{
// Set using comparison function.
// Have to pass the function pointer in the constructor so it knows
// which function to call. The syntax could be cleaned up with some
// typedefs.
std::set<Property<std::string, std::string>,
bool(*)(const Property<std::string, std::string>&,
const Property<std::string, std::string>&)>
set1(&property_less_function<std::string, std::string>);
// Set using comparison functor. Don't have to pass a value for the functor
// because it will be default constructed.
std::set<Property<std::string, std::string>, PropertyLess<std::string, std::string> > set2;
}
请记住,不管使用什么函数,函数都必须定义您的类型的严格弱排序。
Keep in mind that whatever less-than function you use, that function must define a strict weak ordering for your type.
这篇关于c ++集合容器的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!