【发布时间】:2021-12-06 17:02:45
【问题描述】:
我应该使用什么? bool compare 还是 sCompare() 仿函数?为什么? 使用这两个选项有什么区别吗?
struct Dog
{
int m_age{};
int m_weigt{};
};
bool compare(const Dog& a, const Dog& b)
{
return a.m_age > b.m_age;
}
struct sCompare
{
bool operator()(const Dog& a, const Dog& b)
{
return a.m_age > b.m_age;
}
};
int main()
{
vector<Dog> dogs{ Dog{1,20}, Dog{2,10}, Dog{3,5}, Dog{10,40} };
//sort(begin(dogs), end(dogs), compare); this
//sort(begin(dogs), end(dogs), sCompare()); or this
return 0;
}
【问题讨论】:
-
如果它用于代码中的单个位置:两者都不是。请改用 lambda。
-
相关/重复:Should I use functions or stateless functors?(虽然这是个超级老问题,仍在使用
std::binary_function) -
假设我不能在我的代码中的一个地方使用它。我应该使用 lambda 吗?
-
operator()应该是const。否则没有区别。
标签: c++ function boolean overloading functor