Discussion:
std::find - tricky question
(too old to reply)
Frank
2013-01-28 11:18:45 UTC
Permalink
Dear people,

I have a custom class (myclass) and a std::vector<myclass> of objects.
Now I'd like to std::find a certain object, the criterium
is an integer member variable in the class. So if the
integer variable fits an integer I provide, the object was found.

The integer (i) is set in one of the constructors of the class:

myclass obj(par1, par2, i);

Up to now, I std::find like this:

std::find(vec.begin(), vec.end(), myclass(0, 0, 33));

where 33 is the integer to be looked for,
myclass provides a proper "equals" operator.

Now the question: Is it possible to do this without
constructing a dummy object? Of course I could
write my own find function to do this but I'd rather
not if STL already provides a mechanism for it.

TIA!
Miles Davies
2013-08-19 14:38:57 UTC
Permalink
Post by Frank
Dear people,
I have a custom class (myclass) and a std::vector<myclass> of objects.
Now I'd like to std::find a certain object, the criterium
is an integer member variable in the class. So if the
integer variable fits an integer I provide, the object was found.
myclass obj(par1, par2, i);
std::find(vec.begin(), vec.end(), myclass(0, 0, 33));
where 33 is the integer to be looked for,
myclass provides a proper "equals" operator.
Now the question: Is it possible to do this without
constructing a dummy object? Of course I could
write my own find function to do this but I'd rather
not if STL already provides a mechanism for it.
TIA!
use find_if and write a functor.

A class with operator== that only compares one property of the class might lead to future bugs IMHO
Loading...