Trying to save one iteration over my vector.
I have a vector<T>
I need to find a minimum element in the vector.
I am using std::min_element
. Now there is a requirement to create a custom structure, which has elements of <T>
plus few extra, computed on the fly.
So I am trying to use a function with boost::bind()
like this:
MyStruct myStructObj;
typename std::vector< T >::iterator it = std::min_element(V.begin(), V.end(), boost::bind(BuildStructAndFindMin, myStructObj, _1, _2));
but how should I define BuildStructAndFindMin function? Till now, i never needed to create a custom function like this.
-
_1 and _2 represent two ref objects to contents of V. But which one is least of them? I mean: the
std::min_element()'s
definition is going to iterate over a vector. For a fist call, it would simply send first two elements. For a second call, third element from vector and last_found_min element will be sent. Which, _1 or _2 is going to be this last_found_min? How to return an iterator? My vague sketch is like this:std::vector< T >::iterator BuildStructAndFindMin (MyStruct& myStructObj, const T &a, const T &b) { if(<a_min_condition>) // I am aware of this if statement. Just assume it to be a<b { // the point which is greater - create a struct object for that // and push_back in myStructObj return //what?; } else { // the point which is greater - create a struct object for that // and push_back in myStructObj return //what? } }
and after calling this function, I will have a min_element
, but it will not be present in myStructObj. So I will insert it at the beginning.
The whole point in doing this drama is to save one iteration.
The easiest way out would have been: iterate over a vector and build a structure. And then call std::min_element()
. But somehow, I am fighting for few nanoseconds and time is money in this case.
Aucun commentaire:
Enregistrer un commentaire