2017-03-22 43 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