自定义排序和映射时,首选函数指针或函数对象
Prefer function-pointer or function-object when customizing sort and map?
我想在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 );
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针