1

我想在 C++ 中自定义排序模板和地图模板

这里是为了比较,

struct Greater1
{
    bool operator() (string A, string B)
    {
        string AB = A + B;
        string BA = B + A;
        return (AB >BA);
    }
};

static bool Greater2(string A, string B)
{
    string AB = A + B;
    string BA = B + A;
    return (AB >BA);
}

经过我的测试,Greater1 适用于地图,Greater2 适用于排序。我还从 CPLUSPLUS 中获得了一些信息,发现和 map 都应该使用函数指针和函数对象。我的问题是为什么 Greater2 可以用于 map 而 Greater1 可以用于排序。

4

2 回答 2

3

std::sort接受一个Compare对象的实例,而类模板std::map允许您指定Compare. 您可能尝试使用Greater1, 一种类型,如下所示:

sort(beginIt, endIt, Greater1);

这是不正确的。您应该将其用作

sort(beginIt, endIt, Greater1());

但是,由于Greater2是函数指针而不是类型名称,

sort(beginIt, endIt, Greater2);

工作正常。

使用std::map,您需要提供类型。因此,您需要使用类似Greater1. 您还可以使用std::map 构造函数,它允许您指定Compare对象和一些模板魔法,最终使用Greater2如下:

template <typename Key, typename Value, typename Compare>
std::map<Key, Value, Compare> make_map(Compare const& comp)
{
 return std::map<Key, Value, Compare>(comp);
}

你现在可以制作这样的地图:

auto myMap = make_map<std::string, std::string>(Greater2);
于 2015-02-17T00:55:13.877 回答
2

为了交换函数对象和指针,std::map您需要指定函数指针的类型,如下所示

typedef std::function< bool(string,string)> compare;

然后,

std::map<string, string, compare >  m(Greater2) ; 

为了std::sort

sort(beginIt, endIt, Greater1() ); // since Greater1 is type

或者

sort(beginIt, endIt, Greater2 );  
于 2015-02-17T01:04:10.293 回答