c++判断vector中是否存在-1
时间: 2023-11-08 13:02:59 浏览: 46
要判断一个vector中是否存在特定的元素,可以使用std::find函数。在这个例子中,我们可以使用std::find函数来查找vector中是否存在-1,如果存在返回true,否则返回false。
下面是一个示例代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = { 1, 2, 3, 4, 5 };
if (std::find(vec.begin(), vec.end(), -1) != vec.end()) {
std::cout << "The vector contains -1!\n";
}
else {
std::cout << "The vector does not contain -1.\n";
}
return 0;
}
```
在这个示例中,我们首先定义了一个包含整数的vector,然后使用std::find函数查找-1是否存在于vector中。如果-1存在于vector中,则输出"The vector contains -1!",否则输出"The vector does not contain -1."。
相关问题
c++ 判断std::vector中元素是否存在
在C++中,我们可以使用`std::find`算法来判断`std::vector`中元素是否存在。`std::find`算法在`<algorithm>`头文件中定义,它接受两个迭代器和一个值作为参数,返回一个迭代器,指向第一个等于该值的元素。如果该值不存在于容器中,则返回指向容器尾部的迭代器。
下面是一个示例代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> myVec = {1, 2, 3, 4, 5};
if (find(myVec.begin(), myVec.end(), 3) != myVec.end())
{
cout << "Element 3 exists in the vector" << endl;
}
else
{
cout << "Element 3 does not exist in the vector" << endl;
}
if (find(myVec.begin(), myVec.end(), 6) != myVec.end())
{
cout << "Element 6 exists in the vector" << endl;
}
else
{
cout << "Element 6 does not exist in the vector" << endl;
}
return 0;
}
```
输出结果为:
```
Element 3 exists in the vector
Element 6 does not exist in the vector
```
在上面的示例代码中,我们使用`find`算法来判断`myVec`中是否存在值为3和6的元素,输出相应的结果。如果`find`算法返回的迭代器指向容器尾部,则说明该值不存在于容器中。
C++判断Vector里存在的峰值个数
峰值是指一个元素大于其相邻元素,可以采用遍历一遍vector,判断当前元素是否大于前后相邻元素来实现。
以下是示例代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int peakCount(vector<int> arr) {
int count = 0;
for(int i = 1; i < arr.size() - 1; i++) {
if(arr[i] > arr[i-1] && arr[i] > arr[i+1]) {
count++;
}
}
return count;
}
int main() {
vector<int> arr = {1, 2, 3, 4, 3, 2, 1};
int count = peakCount(arr);
cout << "The number of peaks in the vector is: " << count << endl;
return 0;
}
```
输出结果为:
```
The number of peaks in the vector is: 2
```