C++判断list中存在某种值
时间: 2023-09-01 12:08:06 浏览: 200
要判断C++ STL中的list中是否存在某个值,可以使用find()函数,它会返回指向该值的迭代器,如果没有找到,则返回end()迭代器。例如:
```c++
#include <iostream>
#include <list>
int main() {
std::list<int> mylist = { 1, 2, 3, 4, 5 };
// 判断mylist中是否存在值为3的元素
if (std::find(mylist.begin(), mylist.end(), 3) != mylist.end()) {
std::cout << "Found 3 in list!" << std::endl;
} else {
std::cout << "Did not find 3 in list." << std::endl;
}
return 0;
}
```
输出:
```
Found 3 in list!
```
如果要判断的值是一个类对象,可以自定义该类的==运算符,然后通过find()函数来查找。
相关问题
c++判断set中是否有某个值
在 C++ 的 set 容器中,要判断是否存在某个值,可以使用 find 函数来查找。find 函数会在 set 中查找指定元素,如果找到了,返回指向该元素的迭代器;如果没有找到,返回 set 的 end 迭代器。
例如,下面的代码演示了如何使用 find 函数来查找 set 中是否存在某个值:
```c++
#include <set>
#include <iostream>
int main()
{
std::set<int> s = { 1, 2, 3, 4, 5 };
int x = 3;
auto it = s.find(x);
if (it != s.end())
{
std::cout << "Found " << x << " in set" << std::endl;
}
else
{
std::cout << x << " not found in set" << std::endl;
}
return 0;
}
```
在上面的代码中,我们首先创建了一个 set 对象,并使用 find 函数查找 set 中是否存在值为 3 的元素。由于 set 中存在值为 3 的元素,因此 find 函数返回指向该元素的迭代器,if 语句输出 Found 3 in set。
如果要判断 set 中是否存在某个值,也可以使用 count 函数。count 函数会返回 set 中等于指定值的元素个数,因此如果元素个数大于 0,就表示 set 中存在指定值。例如,下面的代码演示了如何使用 count 函数来判断 set 中是否存在某个值:
```c++
#include <set>
#include <iostream>
int main()
{
std::set<int> s = { 1, 2, 3, 4, 5 };
int x = 3;
if (s.count(x) > 0)
{
std::cout << "Found " << x << " in set" << std::endl;
}
else
{
std::cout << x << " not found in set" << std::endl;
}
return 0;
}
```
在上面的代码中,我们使用 count 函数来判断 set 中是否存在值为 3 的元素。由于 set 中存在值为 3 的元素,因此 count 函数返回值大于 0,if 语句输出 Found 3 in set。
判断数组是否存在某值c++
可以使用循环遍历数组来判断是否存在某个值,如下所示:
```c++
bool isExist(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return true;
}
}
return false;
}
```
其中,arr是待判断的数组,size是数组的大小,target是需要查找的值。函数会遍历数组中的每一个元素,如果找到了与target相等的元素,则返回true,否则返回false。