stl 检查容器里面有没有相同项的函数是什么?
时间: 2023-10-21 22:03:44 浏览: 44
STL(标准模板库)提供了许多算法函数来处理容器。要检查容器中是否存在相同项,可以使用 `std::adjacent_find` 算法函数。
`std::adjacent_find` 函数接受两个迭代器作为参数,并在区间内查找相邻元素相等的第一个位置。如果找到相同项,则返回指向该位置的迭代器;否则,返回指向区间末尾的迭代器。
以下是使用 `std::adjacent_find` 函数检查容器中是否存在相同项的示例代码:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11};
auto it = std::adjacent_find(numbers.begin(), numbers.end());
if (it != numbers.end()) {
std::cout << "Found a pair of adjacent elements with the same value: " << *it << std::endl;
} else {
std::cout << "No adjacent elements with the same value found." << std::endl;
}
return 0;
}
```
上述代码中,我们创建了一个 `std::vector` 容器 `numbers`,其中包含了一些整数。然后,我们使用 `std::adjacent_find` 函数来查找相邻元素相等的第一个位置。如果找到了相同项,我们输出该值;否则,输出未找到相同项的消息。
注意:`std::adjacent_find` 函数默认使用 `operator==` 进行元素比较,因此容器中的元素类型需要支持相等比较运算符(`==`)。如果需要使用自定义的比较函数,可以提供一个谓词作为额外的参数给 `std::adjacent_find` 函数。