c++中如何判断对象是否存在与列表中
时间: 2024-05-06 10:14:53 浏览: 10
在C++中,可以使用STL中的find函数来判断一个对象是否存在于列表中。find函数接受两个迭代器作为参数,表示查找范围,以及要查找的元素值。如果元素存在于列表中,则返回指向该元素的迭代器,否则返回指向列表末尾的迭代器。
下面是一个示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> vec = {1, 2, 3, 4, 5};
// 判断元素2是否存在于vec中
if (find(vec.begin(), vec.end(), 2) != vec.end())
{
cout << "2 exists in vec." << endl;
}
else
{
cout << "2 doesn't exist in vec." << endl;
}
// 判断元素6是否存在于vec中
if (find(vec.begin(), vec.end(), 6) != vec.end())
{
cout << "6 exists in vec." << endl;
}
else
{
cout << "6 doesn't exist in vec." << endl;
}
return 0;
}
```
输出结果为:
```
2 exists in vec.
6 doesn't exist in vec.
```
在该示例中,我们使用了vector容器,并使用find函数判断元素2和元素6是否存在于vec中。如果元素存在,则输出相应的提示信息。