set::find non-existing candidate, stuck the code?

I was trying to use the set::find and set::erase function for a customized struct type.
To test the situation where it is asked to find and erase a non existing candidate, I used to code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <set>

struct number {
  int id;
  int value;
  
  bool operator<(const number& rhs) const
  {
    return id < rhs.id;
  }
  
  bool operator==(const number& rhs) const
  {
    return id == rhs.id;
  }
};

int main ()
{
  std::set<number> myset;
  std::set<number>::iterator it;

  // set some initial values:
  for (int i=1; i<=5; i++) {
      number anumber;
      anumber.id = i;
      anumber.value = 10*i;
      myset.insert(anumber);    // set: 10 20 30 40 50
  }
  
  number numbertofind; numbertofind.id = 6;
  it=myset.find(numbertofind);
  myset.erase (it);

  std::cout << "myset contains:";
  for (it=myset.begin(); it!=myset.end(); ++it)
    std::cout << ' ' << it->value;
  std::cout << '\n';

  return 0;
}


this results in empty output with no error. It looks like the code got stuck.

if change line 32 to number numbertofind; numbertofind.id = 3;
The output is:
 
myset contains: 10 20 40 50


What I want to achieve is to be able to detect that I was trying to find an non existing candidate, and skip it.
It will be surprising if <set> could not do this, but I just could not figure out how.

Thank you very much in advance.
Last edited on
1
2
if (it == myset.end())
    //not found 
Great! Thank you so much for your perfect instant reply!
Topic archived. No new replies allowed.