2014-04-01 39 views
0

我試圖使用這些函數來查找我的向量(向量可能爲)的上下界。結構數據包含3個字符串,我使用字符串日期進行比較。C++中的upper_bound/lower_bound函數

bool myCompare(Data &a, Data &b) { 
     return (a.date == b.date); 
} 

#include <algorithm> 

    std::vector<Data>::iterator iterl, iteru; 
    sort(possible.begin(), possible.end(), compare); 
    iterl = std::lower_bound(possible.begin(), possible.end(), struct1, myCompare); 
    iteru = std::upper_bound(possible.begin(), possible.end(), struct2, myCompare); 

但這樣做,編譯displayng以下消息:

Main.cpp:95:18: note: in instantiation of function template specialization 'std::__1::upper_bound<std::__1::__wrap_iter<data *>, 
data, bool (*)(data &, data &)>' requested here 
iteru = std::upper_bound(possible.begin(), possible.end(), struct2, myCompare); 

什麼要使用這些功能的正確方法?

+1

你應該用嚴格的弱序謂詞(例如小於)來比較使用謂詞:a.date AlexT

+0

最好使用const引用:'bool myCompare(const Data&a,const Data&b)' – AlexT

回答

1

比較對象的簽名是bool cmp(const Type1 &a, const Type2 &b);,您需要將const添加到參數myCompare

1

也許,你能做的最好的就是定義操作<的日期,並且不與算法明確地

bool operator<(const Data& lhs, const Data& rhs) 
{ 
    return lhs.date < rhs.date; 
} 

std::vector<Data>::iterator iterl, iteru; 
sort(possible.begin(), possible.end()); 
iterl = std::lower_bound(possible.begin(), possible.end(), data1); 
iteru = std::upper_bound(possible.begin(), possible.end(), data2);