How to find a value in a sorted vector (C++) -
i have searched solution problem, did not find answer. following code learning purposes. want erase elements value 3 in vector:
std::vector<int> v{1,1,2,2,2,3,3,4,4};
i tried solve this:
//only excerpt code
iterator erase(t const& elem) { return v.erase(std::remove(v.begin(), v.end(), elem), v.end()); }
but in test case, expect have iterator point value 4, in code points value 3. removes first 3 vector.
how can remove both values "3", iterator returned points 4?
thank help!
although std::remove
work, doesn't take advantage of fact container sorted. that, need find range contains of target values. this:
#include <algorithm> #include <vector> void remove(std::vector<int>& vec, int value) { auto lb = std::lower_bound(vec.begin(), vec.end(), value); auto ub = std::upper_bound(vec.begin(), vec.end(), value); vec.erase(lb, ub); }
Comments
Post a Comment