在std::vector中查找索引

Finding index in std::vector

本文关键字:查找 索引 vector std      更新时间:2024-04-27

我是C++的新手。如果向量中有一个子集,我试图找到元素的索引。

我的代码在下面。。请帮我解决这个问题。

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
std::vector<uint8_t> v = { 1,2,3,4,0,6,7,8,4,5,6 };
int key = 4;
std::vector<uint8_t>::iterator itr = std::find(v.begin(), v.end(), key);

if (itr != v.cend()) {
uint8_t index = std::distance(v.begin(), itr);
if ((++index == 5) && (++index == 6))
std::cout << "Element present at index " << index-2;
else
continue;
}
else {
std::cout << "Element not found";
}

return 0;
} 

在上面的代码中,如果4,5,6是连续的元素,我想打印元素'4'的索引。

输出:8

您必须将第一个if替换为具有相同测试的while,将两个++index替换为*(++itr),在打印前不减去2进行索引,并将最后一个else替换为if(itr == v.cend())以获得所需输出。

请注意,例如,如果您将期望的查找元素从{4,5,6}更改为{4,4,6},则此代码将不再有效,因此,如果您想对问题进行泛化,我建议您更改问题的一般方法