2017-03-22 44 views
0

这是我的代码“更大的”仿函数会产生编译错误

#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; 

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

+0

请注意,您的注释类不是一个模板,但它的一个方法是。因此,你不能有更大的类型,只是“更大”。 – MSalters

回答

0

你不包括functional

std::vector。它要求你指定一个类型T,以及可选的分配器。你不能给它比较,这是没有道理的!

这样,声明int类型的vector应该是这样的:

std::vector<int> v; 

std::sort另一方面发生在对应于一个范围内的两个迭代器和任选,比较器。你可以在这样的递减顺序排序向量:

#include <vector> 
#include <algorithm> // Required for std::sort 
#include <functional> // Required for std::greater 

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

如有疑问,请咨询Cpp Reference

+0

任何反馈,downvoter? –

+0

非常感谢你,你知道我想要什么,我没有包括,我只是不知道它〜 – manlei

+0

你能解释什么是函数对象吗? – manlei

1

std::mapstd::set需要一个谓词(comporator)来比较容器的元素。默认情况下,它将是std::lessstd::vector不需要比较器。

您需要更正以下行

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

vector<int> a; 

如果你想在升序排序,你可以通过谓语std::greater作为参数之一,如下所示:

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

我以前不知道 manlei