在std::vector中查找多个元素可以通过以下步骤实现:
下面是一个示例代码:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
std::vector<int> elementsToFind = {3, 6, 9};
std::vector<int> foundIndices;
for (const auto& element : elementsToFind) {
auto it = std::find(vec.begin(), vec.end(), element);
if (it != vec.end()) {
foundIndices.push_back(std::distance(vec.begin(), it));
}
}
std::cout << "Found indices: ";
for (const auto& index : foundIndices) {
std::cout << index << " ";
}
std::cout << std::endl;
return 0;
}
在这个示例中,我们有一个std::vector vec,其中包含了一些整数。我们要查找的多个元素存储在elementsToFind中。我们创建了一个新的std::vector foundIndices来存储找到的元素的索引。然后,我们遍历elementsToFind中的每个元素,使用std::find函数在vec中查找该元素。如果找到了该元素,我们将其索引添加到foundIndices中。最后,我们输出foundIndices中存储的索引。
这是一个简单的示例,你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云