比较C ++中的结构

Comparing struct in c++

有谁知道通用方法struct声明比较函数以便我可以在中使用它排序,优先级队列,映射,设置...

我也会知道在声明具有结构作为键的数据结构(如 map )时如何指定比较函数(在我有两个或更多比较函数的情况下)

提前致谢

方法怎么可以"general"?

假设你有这个结构。

struct MyStruct{
    A a; // A is your own class
};

编译器如何知道如何比较类型 A 的对象?

你需要自己定义一个比较运算符。

bool operator()(const MyStruct& s1, const MyStruct& s2);

在创建 std::map.

时,可以将此函数作为比较函数给出
explicit map (const key_compare& comp = key_compare(),
          const allocator_type& alloc = allocator_type());

std::map

comp: Binary predicate that, taking two element keys as argument, returns true if the first argument goes before the second argument in the strict weak ordering it defines, and false otherwise.

默认为

less<key_type>

比较函数取决于结构的语义。你的类型 a < b 是什么意思?

一般来说,比较函数是这样的(引用是可选的):

bool comp( const YourType& a, const YourType& b );

要使地图使用您的比较功能,您必须这样写:

#include <map>

struct YourType{
    int v;
};

struct YourTypeComparison{
    bool operator()( const YourType& a, const YourType& b ) { return a.v < b.v; }
};

int main()
{
    std::map<YourType,int, YourTypeComparison> m;
}

通常您会使用 std::map< std::string, int > 等标准容器。但它们也有 Comparator 类型和 Allocator 类型。

默认使用的Comparator是std::less,看起来有点像这样,

template <class T>
struct less : binary_function <T,T,bool> {
    bool operator() (const T& x, const T& y) const {
        return x<y;
    }
};

(还有一些其他已经制作好的函子http://en.cppreference.com/w/cpp/utility/functional

请注意,它将两个对象与 < 进行比较。这意味着作为 "general method" 你只需要实现运算符 bool operator< (const X& lhs, const X& rhs){...} 就可以对你的对象进行排序。参见 Operator Overloading FAQ。根据经验,如果您要实现一个比较运算符,那么您也应该实现其他的。

如果您需要以其他方式对键进行排序,您可以定义自己的比较器(仿函数)。

template < class T >
struct myLess {
    bool operator()( const T& lhs, const T& rhs ) const {
        return lhs < rhs;
    }
};

并在像 std::map< int, int, myLess<int> > 这样的地图中使用它。

如果你只需要比较一种类型,你也可以完全不使用模板。

struct myLess {
    bool operator()( const int& lhs, const int& rhs ) const {
        return lhs < rhs;
    }
};

那你只需要写std::map< int, int, myLess >.

请记住,您要比较的对象是键类型,不一定是包含类型。