fork download
  1. #include <vector>
  2. #include <iostream>
  3. #include <algorithm>
  4.  
  5. struct Foo {
  6. int id;
  7. // ... more members ... //
  8. Foo(int id) : id(id) {std::cout << "created " << id << "\n";}
  9. };
  10.  
  11. bool sortById(const Foo& a,const Foo& b) { return a.id < b.id; }
  12. bool compareToId(const Foo& a,const int& b) { return a.id < b; }
  13.  
  14. int main(int argc, char *argv[])
  15. {
  16. std::vector<Foo> vect;
  17. vect.push_back(10);
  18. vect.push_back(123);
  19. vect.push_back(0);
  20. vect.push_back(1);
  21. std::sort(vect.begin(),vect.end(),sortById);
  22. int id_to_find = 42;
  23. std::vector<Foo>::iterator f = std::lower_bound(vect.begin(),vect.end(),id_to_find,compareToId);
  24. if (f != vect.end() && f->id == id_to_find) { std::cout << "FOUND"; }
  25.  
  26. }
  27.  
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
created 10
created 123
created 0
created 1