0

I have a vector filled with client class objects sorted by name. The problem starts when I try to get the "highest" name(string class) searched.

A brief example of my problem:

int main()
{
  vector<Client> vCli;
  vector<Client>::iterator low;
  vector<Client>::iterator up;

  myClass c1(1, "John Lil", 123);
  myClass c2(2, "John Bob", 325);
  myClass c3(3, "Alves Hunk", 472);
  myClass c4(4, "Gil Diniz", 521);
  myClass c5(5, "Boll Yo", 181);

  c_Cli.push_back(c1);
  c_Cli.push_back(c2);
  c_Cli.push_back(c3);
  c_Cli.push_back(c4);
  c_Cli.push_back(c5);

  sort(vCli.begin(), vCli.end(), auxPesqNome[](Cliente a, Cliente b) {return a.name < b.name;} );
  /* Correct sort = Alves Hunk, Boll Yo, Gil Diniz,John Bob ,John Lil  */


  low = lower_bound (vCli.begin(), vCli.end(), "John", [](Cliente a, Cliente b) {return a.name < b.name;});
  up  = upper_bound (vCli.begin(), vCli.end(), "John", [](Cliente a, Cliente b) {return a.name < b.name;});

  cout << (low - vCli.begin()) << endl; 
  /* Correct output  = 3 */

  cout << (up - vCli.begin()) << endl;
  /* ***INCORRECT output  = 3 *** */


  return 0
}

I think the problem may be in compound names, but my little experience in c ++ can't solve it.

I would like to replace "lower_bound" and "upper_bound" with "equal_range".

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 3
    Please make sure examples you provide can be compiled. By the time I'm done patching up all of the compiler errors in this code I'll probably have accidentally fixed the error you're looking for. Use [mcve] as inspiration. – user4581301 Nov 18 '19 at 20:06
  • `John Bob` is *greater* than `John`. `upper_bound` returns the iterator to the first element that is greater than `John`, which is `vCli.begin() + 3`. – ph3rin Nov 18 '19 at 20:07
  • what is "the problem" what output did you expect and why? – 463035818_is_not_an_ai Nov 18 '19 at 20:08
  • Unrelated: if you compile to one of the modern standards (C++11 or newer) you can use [List Initialization](https://en.cppreference.com/w/cpp/language/list_initialization) to save yourself a bunch of effort setting up the `vector`. Eg: `vector vCli{{1, "John Lil", 123}, {2, "John Bob", 325}, ...};` All of the `cN` variables and the `push_back`s are no longer needed. – user4581301 Nov 18 '19 at 20:11
  • @user4581301 I'm studying it yet. Thank you – Diego Hilário Nov 18 '19 at 20:20

0 Answers0