I have the following code (compiler: MSVC++ 10):
std::vector<float> data;
data.push_back(1.0f);
data.push_back(1.0f);
data.push_back(2.0f);
// lambda expression
std::for_each(data.begin(), data.end(), [](int value) {
// Can I get here index of the value too?
});
What I want in the above code snippet is to get the index of the value in the data vector inside the lambda expression. It seems for_each only accepts a single parameter function. Is there any alternative to this using for_each and lambda?
maybe in the lambda function, pass it a
int&
instead of value int, so you'd have the address. & then you could use that to deduce your position from the first itemwould that work? i don't know if for_each supports references
I don't think you can capture the index, but you can use an outer variable to do the indexing, capturing it into the lambda:
This prints 3, as expected, and
j
holds the value of the index.If you want the actual iterator, you maybe can do it similarly:
I think that the simplest way is to use
std::accumulate
:This solution works with any container and it don't require a variable or custom classes.
Following the standard convention for C and C++, the first element has index 0, and the last element has index size() - 1.
So you have to do the following;-