gpt4 book ai didi

c++ - std::greater() 预期 0 个参数(或 1 个参数),提供 2 个,为什么?

转载 作者:太空狗 更新时间:2023-10-29 20:57:36 24 4
gpt4 key购买 nike

这是在STL头文件中定义的:

template<typename _Tp>
struct greater : public binary_function<_Tp, _Tp, bool>
{
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x > __y; }
};

我只写了一行简单的代码如下:

cout << (std::greater<int>(3, 2)? "TRUE":"FALSE") << endl;

它不编译。错误信息是:

C:\Qt\Tools\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_function.h:222: std::greater<int>::greater()
struct greater : public binary_function<_Tp, _Tp, bool>
^
C:\Qt\Tools\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_function.h:222: note: candidate expects 0 arguments, 2 provided
C:\Qt\Tools\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_function.h:222: std::greater<int>::greater(const std::greater<int>&)
C:\Qt\Tools\mingw482_32\i686-w64-mingw32\include\c++\bits\stl_function.h:222: note: candidate expects 1 argument, 2 provided

怎么了?编译器当然是 minGW (GCC)。

这是我的代码的简化版本。事实上,我在复杂的排序算法中使用了 std::greater。

最佳答案

std::greater<...>是一个类,不是一个函数。此类已重载 operator() ,但您需要一个类的对象来调用该运算符。所以你应该创建一个类的实例,然后调用它:

cout << (std::greater<int>()(3, 2)? "TRUE":"FALSE") << endl;
// #1 #2

此处第一对括号 ( #1 ) 创建了一个 std::greater<int> 的实例, 和 #2电话 std::greater<int>::operator()(const int&, const int&) .

关于c++ - std::greater<int>() 预期 0 个参数(或 1 个参数),提供 2 个,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30031859/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com