【问题标题】:Functor or boolean comparator函子或布尔比较器
【发布时间】: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


【解决方案1】:

您的两个比较器导致相反的顺序(&lt;&gt;)。除此之外最大的区别是你不能在函数中定义函数,但你可以在函数中定义类型。此外,lambda 表达式提供了直接的语法来做到这一点:

int main()
{
    vector<Dog> dogs{ Dog{1,20}, Dog{2,10}, Dog{3,5}, Dog{10,40} };
    sort(begin(dogs), end(dogs), [](const Dog& a,const Dog& b){ return a.m_age < b.m_age;});
    // or 
    auto comp = [](const Dog& a,const Dog& b){ return a.m_age < b.m_age;}
    sort(begin(dogs), end(dogs),comp); 

}

【讨论】:

  • 是的,没错,那是个错误,两个比较器应该是 > 和 > 。
  • 这意味着在这种情况下我不应该使用仿函数或函数?
  • @Originalnickname 对于函子,lambda 表达式是 syntactic sugar。通常函子比函数更可取,因为它具有多功能性和更好的优化机会。
  • @user4581301,非常感谢!
  • 如果将比较函数声明为全局函数会在项目的其他地方增加价值,那么也许您可以这样做。您可以改为将 operator
猜你喜欢
  • 1970-01-01
  • 2019-05-28
  • 2012-08-19
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多