c++ - "greater"仿函数给出编译器错误

标签 c++ stdvector

这是我的代码

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

/*
struct greater
{template<class T>
    bool operator()(T const &a, T const &b) const { return a > b; }
};*/

//std::sort(numbers.begin(), numbers.end(), greater());
int main(){
    vector<int,::greater<int>()> a;
    int x;
    while (cin >> x)
        a.push_back(x);
    sort(a.begin(),a.end());

    for (int b : a){
        cout << b << endl;
    }
    return 0;
}

为什么这是错误的?

map<int,int,::greater<int>()> a;

我看过一些博客,他们可以通过,但我不能 我想知道答案

最佳答案

std::map 所需的谓词(comporator)和 std::set比较容器的元素。默认情况下它将是 std::less . std::vector不需要比较器。

您需要更正以下行

 vector<int,::greater<int>()> a;

vector<int> a;

如果你想按升序排序,你可以传递谓词std::greater作为参数之一如下:

std::sort(a.begin(), a.end(), std::greater<int>())

关于c++ - "greater"仿函数给出编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42941702/

相关文章:

c++ - std::vector 的模板推导指南:其他 std 类型的限定/非限定名称

c# - 使用C#/C++,是否可以限制网络流量?

c++ - 是否可以用sizeof对void指针进行算术运算?

c++ - 带数据交换的 std::vector 指针

c++ - IBM i 上 std::vector<std::string> 的最大容量

c++ - 返回(两个)按​​元素添加的 vector 的最大值

c++ - 将 std::vector<char> 截断为长度 N 以释放内存的有效方法

c++ - 为什么隐式转换成员函数重载按返回类型工作,而普通函数不允许这样做?

c++ - 是否有可能/希望创建不可复制的共享指针模拟(以启用 weak_ptr 跟踪/借用类型语义)?

自定义堆栈分配器中的 C++ 内存对齐