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?
The simplest solution is to use the std::find algorithm defined in the <algorithm> header. The idea is to get the index using std::distance on the iterator returned by std::find , which points to the found value. We can also apply pointer arithmetic to the iterators. Therefore, the - operator would also work.
In C++14 thanks to generalized lambda captures you can do something like so:
std::vector<int> v(10); std::for_each(v.begin(), v.end(), [idx = 0] (int i) mutable { // your code... ++idx; // 0, 1, 2... 9 });
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:
int j = 0; std::for_each(data.begin(), data.end(), [&j](float const& value) { j++; }); std::cout << j << std::endl;
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:
std::vector<float>::const_iterator it = data.begin(); std::for_each(data.begin(), data.end(), [&it](float const& value) { // here "it" has the iterator ++it; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With