I want to find a element in an vector suppose:
vector:vector<int> input = {11, 12, 15, 11, 13}; target element:11;
My code:
auto mylambda = [&target](const int &a)
{
return a == target;
};
vector<int>::iterator it = find_if(input.begin(), input.end(), mylambda);
while (it != input.end())
{
cout << "Found item: " << *it << endl;
int index = std::distance(input.begin(), it);
cout << "Index number: " << index << endl;
it++;
it = find_if(it, input.end(), mylambda);
}
It works fine with output:
Found item: 11
Index number: 0
Found item: 11
Index number: 3
I have to have my iterator value also in the lambda function.Consider something like this:
auto mylambda = [&target](const int &a)
{
//cout << distance(input.begin(), it) << endl;
return a == target;
};
The commented line. Is there a way to do it? Thanks in advance.
Since std::vector
stores its data in a contiguous chunk of memory, you can get the index (distance from element 0) of the current element in the lambda by subtracting the address of the current element with the address of the first element - and from that index you can also get an iterator:
auto mylambda = [&](const int &a) {
std::size_t idx = std::distance(&*input.cbegin(), &a);
auto it = std::next(input.begin(), idx);
return a == target;
};
idx
is here the index of the current elementit
is here an iterator to the current elementAlternatively, keep a running counter:
auto mylambda = [&target, idx = 0u](const int &a) mutable {
// idx is here the index of the current element
// auto it = std::next(input.begin(), idx); // if you even need an iterator
++idx;
return a == target;
};