Search value in a functor's c'tor
Say I had a std::vector<std::pair<int, std::vector<int> > >
, that is, a vector containing pairs of ints to vectors. ( I know I could acheive the same thing with a map, but that's not what I'm asking )
How would I search for the int (the one in the pair) using STL? I wrote a solution that works:
struct FindFirst {
FindFirst(int i) : toFind(i) { }
int toFind;
bool operator()
( const std::pair<int, std::vector<int> > &p ) {
return p.first==toFind;
}
};
That can be used like this:
int valueToFind = 4;
std::find_if(myVec.begin(), myVec.end(), FindFirst(valueToFind));
But it looks to me like this a little ugly; there must be a better way. So are there better ways of doing this without using anything from C++0x or Boost? (Bec开发者_开发技巧ause I'm trying to learn the best way of doing it with, and I stress, only STL)
EDIT: Looks like there's a little confusion on what I'm asking. What I'm more interested in is whether it's bad practice to use the constructor for search values on a functor, especially when they are used in STL algo's.
This is the best way to do it, when using only the STL. What exactly do you not like about it (except maybe it's verbosity)?
It is versatile, because you can use with other algorithms like for instance std::binary_search
.
It is quite simple and direct (at least to someone used to C++ functors).
The only thing to really improve here would be the choice of the data-structure. Such use-cases are covered by std::map
, and you have not explained why you cannot use it. I understand that for your real problems a map really might not be suited, but in that case your example is not representative of your actual problem. You should fix that.
why not using direct STL calls
void FindFirst(std::vector<std::pair<int, std::vector<int> > >& v, int intToLookFor)
{
std::vector<std::pair<int, std::vector<int> > >::iterator iItr;
for (iItr = v.begin(); iItr != v.end(); ++iItr)
{
if (iItr->first == intToLookFor) return;
}
}
(Sorry for the variable names ;-)). Also the return value from this function can be an iterator, or a reference to the vector value...
No, it is not a bad practice to pass a parameter to the predicate function. Actually, that makes the predicate quite flexible.
Alternative is to use global variable - which I would call a bad practice to use for predicate.
精彩评论