我想在向量中找到一个元素假设: 向量:向量输入 = {11, 12, 15, 11, 13}; 目标元素:11; 我的代码:
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);
}
输出效果很好: 找到物品:11 索引号:0 找到物品:11 索引号:3
我的迭代器值也必须在 lambda 函数中。考虑这样的事情:
auto mylambda = [&target](const int &a)
{
//cout << distance(input.begin(), it) << endl;
return a == target;
};
注释行。 有办法做到吗? 预先感谢。
由于
std::vector
将其数据存储在连续的内存块中,因此您可以获取 lambda 中当前元素的索引(距元素 0 的距离):
auto mylambda = [&](const int &a) {
auto idx = std::distance(const_cast<const int *>(input.data()), &a);
auto it = std::next(input.begin(), dist);
return a == target;
};
idx
这里是当前元素的索引it
这里是当前元素的迭代器