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::vectorstores 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:idxis here the index of the current elementitis here an iterator to the current elementAlternatively, keep a running counter: