0

I have a function that is taking two pointers as parameters.

bool function(T* a, T* b);

And a container (vector).

vector<T> vector;

I wish to use an algorithm of the STL (the for_each) to apply the function on the elements of the vector. However, I don't know if the pointers of the elements will go automatically in the function as parameters. For example, will

for_each(vector.begin(), vector.end(), function(/*something here?*/))

work, or I need to go with a loop (the new for each in loop of the C++11) ?

3
  • I would honestly think the for_each loop is an akward way to do this, but what is it exactly you are trying to do? Are you wanting for each element of the vector[i], to be put through function(vector[i],vector[i+1]) Commented Apr 8, 2016 at 0:26
  • why not a normal for loop? and access it using [i] Commented Apr 8, 2016 at 0:26
  • Wanted to know if there is a way with algorithms, but yes, I don't have a choice and need the loop. Commented Apr 8, 2016 at 0:55

2 Answers 2

3

You cannot use std::for_each() with your function for at least two reasons:

  • std::for_each passes a single parameter to the lamba, your function() takes two parameters.

  • std::for_each passes a reference to each member of the container, and not a pointer.

Sign up to request clarification or add additional context in comments.

4 Comments

It is possible to write a wrapper function which accepts a reference, obtains pointer to a couple of objects based on that reference, and passes the pointers to function().
Turning a reference into a pointer is straightforward (I'll let you in on a little secret: it usually takes exactly 0 CPU cycles to do that). However, a reference is a reference to a single object, not a "couple of objects".
I used the words "based on" for a reason. There is nothing stopping the wrapper making an assumption that the reference it receives is an element of a std::vector (as is the case in this question). Given the address of one element, it is then possible to reason about the address of other elements.
Sure, but only if you're careful. If you ass-ume that the other object is the one after what for_each() gives you, and you blindly use for_each() on the entire vector, you might spend a lot of time trying to figure out why your code crashes, every time.
1

Try utilizing a normal for loop for solving this problem.

vector<T> v;
for(size_t i(0); i < v.size()-1; ++i)
{
    function(&v[i], &v[i+1]);
}

This will pass as the values an address to elements i and i+1 of v which of type T.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.