2012-03-21 111 views
0

我想使用STL的排序有一類比較功能greater使用infoVec1infoVec2,但我得到一個編譯錯誤:STL排序比較類函數

這裏是類的頭

class Compare{ 
    Compare(); 
    std::vector< std::vector<std::string> >& infoVec1; 
    std::vector< std::vector<std::string> >& infoVec2; 


    public: 

    bool greater(int one, int two); 

    Compare(std::vector< std::vector<std::string> >& info1, 
    std::vector< std::vector<std::string> >& info2); 
}; 

我初始化主比較像這樣:

Compare C = Compare(info1, info2); 

我試圖在主喜歡用大:

sort(vec.begin(), vec.end(), C.greater); 

而且我得到這個錯誤:

main.cpp:266: error: no matching function for call to ‘sort(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, <unresolved overloaded function type>)’ 
/usr/include/c++/4.2.1/bits/stl_algo.h:2852: note: candidates are: void std::sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, _Compare = bool (Compare::*)(int, int)] 
make: *** [main.o] Error 1 

我怎麼能解決這個類,以便greater將與STL排序工作嗎?

+0

什麼類型是'vec'? – Cameron 2012-03-21 03:14:31

+0

比較函數應該是獨立函數或函數對象。 – 2012-03-21 03:16:22

+0

vec是std類型的::矢量 HighLife 2012-03-21 03:19:44

回答

1

它更容易將更大的()方法更改爲operator()()。

class Compare{ 
    Compare(); 
    std::vector< std::vector<std::string> >& infoVec1; 
    std::vector< std::vector<std::string> >& infoVec2; 


    public: 

    bool operator()(int one, int two) const; // this is used automatically. 

    Compare(std::vector< std::vector<std::string> >& info1, 
    std::vector< std::vector<std::string> >& info2); 
};