Stl :: find_if with user find
I was wondering if there is a way to use stl :: find_if to find a user-entered value
I don't know how to do this without using any bad conventions (globals) or adding loads of extended code.
For example, if the user enters int x for 10, then I want to search for the vector ints
iterator = find_if(begin,end,pred) //but how does pred know the user inputted value?
+2
source to share
3 answers
pred
must be an instance of a type with an overloaded () operator, so it can be called as a function.
struct MyPred
{
int x;
bool operator()(int i)
{
return (i == x);
}
};
(Using here struct
for brevity)
std::vector<int> v;
// fill v with ints
MyPred pred;
pred.x = 5;
std::vector<int>::iterator f
= std::find_if(v.begin(),
v.end(),
pred);
Writing custom classes like this (with "loads" of code!) Is cumbersome to say the least, but will be greatly improved in C ++ 0x with the addition of lambda syntax.
+5
source to share