判断vector中是否存在某元素的多种方法
作者:野牛程序员:2023-06-27 21:10:28 C++阅读 3244
在 C++ 中,你可以使用多种方法来判断一个 vector 是否包含某个元素。下面是其中几种常见的方法:
方法 1:使用循环遍历
#include <iostream>
#include <vector>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int target = 3;
bool found = false;
for (int i = 0; i < vec.size(); i++) {
if (vec[i] == target) {
found = true;
break;
}
}
if (found) {
std::cout << "元素存在于 vector 中" << std::endl;
} else {
std::cout << "元素不存在于 vector 中" << std::endl;
}
return 0;
}方法 2:使用 STL 算法 find()
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int target = 3;
auto it = std::find(vec.begin(), vec.end(), target);
if (it != vec.end()) {
std::cout << "元素存在于 vector 中" << std::endl;
} else {
std::cout << "元素不存在于 vector 中" << std::endl;
}
return 0;
}方法 3:使用 STL 算法 count()
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int target = 3;
int count = std::count(vec.begin(), vec.end(), target);
if (count > 0) {
std::cout << "元素存在于 vector 中" << std::endl;
} else {
std::cout << "元素不存在于 vector 中" << std::endl;
}
return 0;
}以上是几种常见的方法,可以根据具体情况选择适合的方法来判断 vector 中是否存在某个元素。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

