Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the index of a value in a vector using for_each?

Tags:

c++

c++11

lambda

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?

like image 613
Liton Avatar asked Sep 20 '10 13:09

Liton


People also ask

How do you find the index of an object in a vector?

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.


2 Answers

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 }); 
like image 117
Tom Avatar answered Sep 29 '22 15:09

Tom


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;  }); 
like image 30
Diego Sevilla Avatar answered Sep 29 '22 15:09

Diego Sevilla