C ++中的upper_bound / lower_bound函数

时间:2014-04-01 08:21:38

标签: c++ lower-bound upperbound

我正在尝试使用这些函数找到我的向量的上限和下限( vector possible )。 struct数据包含3个字符串,我使用 string date 进行比较。

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

但通过这样做,编译器显示以下消息:

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

使用这些功能的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

比较对象的签名为bool cmp(const Type1 &a, const Type2 &b);,您需要将const添加到myCompare的参数中。

答案 1 :(得分:1)

你可以做的最好的事情就是定义运算符&lt; for Date并且不要使用带有算法的谓词

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