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:
#include <iostream>
#include <set>
struct number {
int id;
int value;
booloperator<(const number& rhs) const
{
return id < rhs.id;
}
booloperator==(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.