c++ - How to use lower_bound to insert value into sorted vector -


i have vector of pointer class want keep sorted int key using stl. defined operator < in class a

bool operator< (const &lhs, const &rhs){     return (lhs.key < rhs.key); }; 

and in insert function looks like

vector<a*>::iterator = lower_bound(vec.begin(), vec.end(), element); vec.insert(it, element); 

i expect lower_bound return first place new element can placed, not work. inserting objects keys 0,1,2,3 result in vector in incorrect order (2,3,1,0). why ?

probably use comparator object:

compare function upper_bound / lower_bound

but what's wrong code?

from example, you're using vector of pointers: std::vector<a*>. hence, need define comparison pointers pass in std::lower_bound:

bool less_a_pointer (const a* lhs, const a* rhs) {     return (lhs->key < rhs->key); }  auto = std::lower_bound(vec.begin(), vec.end(), element, less_a_pointer); //... 

of course, question why using pointers in first place - store a objects unless need to. if need store pointers, std::shared_ptr handle you:

std::vector<std::shared_ptr<a>> v; std::shared_ptr<a> element(new a(...)); auto = std::lower_bound(v.begin(), v.end(), element); //will work 

you can use lambda instead of having write free function:

auto = std::lower_bound(v.begin(), v.end(),                            [](const a* lhs, const a* rhs)                           { return lhs->key < rhs->key; }); 

Comments