How to find the first smaller element than an integer X in a vector ? (c++)

别等时光非礼了梦想. 提交于 2019-12-04 11:29:18

cppreference informs me that std::lower_bound

Returns an iterator pointing to the first element in the range [first, last) that is not less than value

and std::upper_bound

Returns an iterator pointing to the first element in the range [first, last) that is greater than value

In this case, given a vector containing 10 10 10 20 20 20 30 30 I would expect both functions to point at the first 20, which sits at position 3 in the vector and is indeed the result you got both times. If you had instead asked for 20, std::lower_bound would return an iterator pointing to the first 20 in the vector (position 3)... the first number not less than 20 and the same result you'd get when asking for 11. In this case though, std::upper_bound would return an iterator pointing at the first 30 (position 6), which is the first value greater than 20.

Just move the iterator back one to get the last value less than your target number, std::prev is one way to do that.

Well upper_bound returns the first item that is greater than the test item, so the one before that (if it exists) will be the one you want?

you could do this...it might be better to return an iterator in case if the vector is empty...

auto find_next_smaller(vector<int> vec, const int x) { 
    std::sort(vec.begin(), vec.end());
    auto it = std::lower_bound(vec.begin(), vec.end(), x); 
    if (it == vec.end()) { 
      it = (vec.rbegin()+1).base();
    }
    else if (it != vec.begin() && *it > x) { 
        --it; 
    }

    return it; 
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!