自定义排序和映射时,首选函数指针或函数对象

Prefer function-pointer or function-object when customizing sort and map?

本文关键字:函数 指针 对象 排序 映射 自定义      更新时间:2023-10-16

我想在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适用于map,Greater2适用于sort。我还从CPLUPLUS中获得了一些信息,发现和map都应该同时使用函数指针和函数对象。我的问题是为什么Greater2可以用于映射,而Greater1可以用于排序。

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

为了与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 );