2015-07-19 59 views
-3

如何排序shared_ptrs C++的向量?我試圖排序一個結構數據對象的share_ptrs矢量。並且還定義了比較器功能。C++ std ::排序share_ptr的向量<objects>

struct data{ 
    int number; 
}; 

bool comparator(const std::shared_ptr<data> &a, const std::shared_ptr<data> &b) { 
    return a->number < b->number(); 
} 

int main() { 
    std::vector<std::shared_ptr<data>> v; 
    std::sort(v.begin(), v.end(), comparator); 
} 

但我得到編譯錯誤:

In file included from /usr/include/c++/4.8/algorithm:62:0, 
       from test.cpp:10: 
/usr/include/c++/4.8/bits/stl_algo.h: In instantiation of ‘void std::__insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<std::shared_ptr<data>*, std::vector<std::shared_ptr<data> > >; _Compare = bool (*)(const A&, const A&)]’: 
/usr/include/c++/4.8/bits/stl_algo.h:2226:70: required from ‘void std::__final_insertion_sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<std::shared_ptr<data>*, std::vector<std::shared_ptr<data> > >; _Compare = bool (*)(const A&, const A&)]’ 
/usr/include/c++/4.8/bits/stl_algo.h:5491:55: required from ‘void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = __gnu_cxx::__normal_iterator<std::shared_ptr<data>*, std::vector<std::shared_ptr<data> > >; _Compare = bool (*)(const A&, const A&)]’ 
test.cpp:110:45: required from here 
/usr/include/c++/4.8/bits/stl_algo.h:2159:29: error: invalid initialization of reference of type ‘const A&’ from expression of type ‘std::shared_ptr<data>’ 
..... 
+4

'b-> number();'< - 刪除括號。然後[它有效](http://coliru.stacked-crooked.com/a/49c391d12679a140)。 –

+0

比較中的壞括號 –

回答

3
return a->number < b->number(); 

必須是:

return a->number < b->number; 

但是,我不知道如果這是你真正的代碼和編譯器所使用。你應該得到更清晰的錯誤信息,例如:

的Visual C++ 2013:

error C2064: term does not evaluate to a function taking 0 arguments 

GCC v4.8.3:

error: expression cannot be used as a function 
    return a->number < b->number(); 
           ^

PS:你應該張貼您的完整代碼當詢問這些問題時全部爲#include。在你的情況下,<vector><algorithm><memory>