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) ?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.