2013-02-09 37 views
0

。 但是,当我用vector替换set,因此使用push_back函数代替insert函数时,一切正常。任何人都可以解释我做错了什么? 谢谢你的建议。问题与C++当我尝试编译下面的代码设置容器

+0

如果你不关心排序,你可能想尝试一下'std :: unordered_set',这在你看来并不在这里,根据你得到的错误来判断,我已经从编译这个错误我的脑子。 – chris 2013-02-09 03:34:28

+0

@chris因为你必须提供一个散列和相等运算符,所以它可能会使用'std :: unordered_set'更多的工作。 – Rapptz 2013-02-09 03:44:08

+0

@Rapptz,确实,尽管订购在我看来并不像它在这里很突出。 – chris 2013-02-09 03:46:33

回答

3

std::set将其值存储在已排序的二叉树中,因此它需要知道如何比较它所保存的值。默认情况下,它使用std::less作为比较函数,对于非专用用户定义类型,它尝试调用operator<。所以,说一套如何比较你的对象最简单的方法是定义一个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模板类:

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

另一种是用正确的签名功能,或具有与正确的签名定义的operator()一个类来替代默认的比较类型。这是事情开始变得丑陋的地方。

// 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; 
} 

请记住,任何低于你使用的功能,该功能必须定义您的类型strict weak ordering

+0

非常感谢您的明确解释。 – 2013-02-09 21:54:25

2

为了在std::set中插入一些东西,您需要定义operator<

例如该编译罚款GCC 4.7.2:

#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); 
    } 
    bool operator<(const Property& p2) const { 
     //Something naive.. 
     return p < p2.p; 
    } 

}; 

int main() 
{ 
set< Property<string, string> > properties; 
Property<string, string> name("name", "Andy"); 

properties.insert(name); 

} 

另一种方法是使用std::unordered_set尽管这将要求您提供钥匙并定义operator==哈希值。

+0

代码不会在我的VC编译:) – billz 2013-02-09 03:53:58

+0

@billz当然,我只尝试过GCC 4.7.2。 – Rapptz 2013-02-09 03:55:02

+0

对已经有'operator <',为什么不只是'p billz 2013-02-09 03:56:58