stdvector 中查找是否存在指定元素
在std::vector中查找是否存在指定元素,可以使用std::find函数来实现。该函数会在给定范围内查找指定元素,并返回一个指向该元素的迭代器,如果找不到,则返回指向范围末尾的迭代器。
示例代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
int target = 3;
auto it = std::find(nums.begin(), nums.end(), target);
if (it != nums.end()) {
std::cout << "Element found at index: " << std::distance(nums.begin(), it) << std::endl;
} else {
std::cout << "Element not found" << std::endl;
}
return 0;
}
在上述示例中,我们定义了一个std::vector,并使用std::find函数在其中查找元素3。如果找到了,则输出元素的索引,否则输出"Element not found"。
注意,需要包含algorithm头文件来使用std::find函数
原文地址: http://www.cveoy.top/t/topic/ii7J 著作权归作者所有。请勿转载和采集!