cpp- lower_bound返回错误的迭代器

时间:2016-03-30 11:44:24

标签: c++ vector

我有以下类Sudent,其函数名为isFail()。如果等级< = 60,则此函数返回true,否则返回false。

class Student
{
    public:
        Student(std::string name_ , int const id_);
        virtual ~Student();
        void addGrade(int const grade2add);//grade above 100
        void removeGrade (int const grade2remove);  //update maxGrade
        bool isFail();//60-fail
        void print(); //id, name, grades

    private:
        std::string name;  //max 20 chars
        int const id; //5 digits, only digits
        std::vector<int> grades;

};

我实现了isFail函数:

bool Student::isFail()
{
    int temp= *lower_bound(grades.begin(), grades.end(), 61);
    if (temp <= 60)
        return true;
    else
        return false;
}

出于某种原因,我看到以下情况: [100,98,96,60,95] Temp等于100(第一个元素)而不是60。

p.s包含了所有相关的库以及使用命名空间std。

我阅读了http://www.cplusplus.com/reference/algorithm/lower_bound/中的文档,根据他们的例子,它应该有效。

如果有更好的方法,请建议。

2 个答案:

答案 0 :(得分:7)

std::lower_bound正在返回正确的迭代器,它只是没有做你想要的。它返回第一个元素,该元素不小于该值。在您的情况下,向量[100,98,96,60,95]的第一个元素为100.

也许请看一下std::min_element?毕竟最小元素似乎是你正在寻找的。 http://en.cppreference.com/w/cpp/algorithm/min_element

答案 1 :(得分:1)

来自std::lower_bound

的文档
  

返回指向范围中第一个元素的迭代器[first,first   最后)不小于(即大于或等于)值。

所以,lower_bound似乎不是你想要的未排序数组。如果您仍想使用lower_bound,您还应该考虑该文档说:

  

范围[first,last]必须至少部分排序

如果要查找最接近61但低于61的元素,则应首先对数组进行排序,或者编写自己的算法来跟踪最接近的元素但必须遍历所有数字。