简体   繁体   中英

cpp- lower_bound returns the wrong iterator

I have the following class Sudent with a function called isFail(). This function returns true if there is a grade<=60, and false if not.

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;

};

I implement the isFail function:

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

For some reason I see that in case of the following grased: [100,98,96,60,95] Temp is equal to 100 (the first element) instead of 60.

ps all the relevant libraries are included plus using namespace std.

I read the documentation in http://www.cplusplus.com/reference/algorithm/lower_bound/ , and according their example it supposed to work.

IF there is better way to do it please suggest.

std::lower_bound is returning the right iterator, it just doesn't do what you want. It returns the first element that is not less than the value. In your case, the first element of your vector [100,98,96,60,95] is 100.

Maybe take a look at std::min_element instead? After all the minimum element seems to be what you are looking for. http://en.cppreference.com/w/cpp/algorithm/min_element

From the documentation of std::lower_bound

Returns an iterator pointing to the first element in the range [first, last) that is not less than (ie greater or equal to) value.

So, lower_bound seems not to be what you are looking for for an unsorted array. If you would like to use lower_bound anyways, you should also consider that the doc says:

The range [first, last) must be at least partially ordered

If you want to find the element that is closest to 61 but lower than 61, you should either sort your array first or write an own algorithm that would keep track of the closest element but had to go through all numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM