stl向量
Given a vector and an element to be searched in the vector.
给定一个向量和要在向量中搜索的元素。
To check whether an elements exists in a vector or not – we use find() function. find() function takes 3 arguments.
要检查向量中是否存在元素 –我们使用find()函数 。 find()函数带有3个参数。
Syntax:
句法:
find(InputIterator first, InputIterator last, const T& element);
Parameters:
参数:
InputIterator first – an iterator pointing to the first elements (or elements from where we have to start the searching).
InputIterator first –指向第一个元素(或我们必须从其开始搜索的元素)的迭代器。
InputIterator last – an iterator pointing to the last elements (or elements till then we have to find the element).
InputIterator last –指向最后一个元素(或直到现在我们必须找到该元素的元素)的迭代器。
element – and elements of same type to be searched.
element –和要搜索的相同类型的元素。
If the element exists – it returns an iterator to the first element in the range that compares equal to element (elements to be searched). If the element does not exist, the function returns last.
如果元素存在–它将迭代器返回到与元素 (等于要搜索的元素)相等的范围内的第一个元素。 如果该元素不存在,则该函数最后返回。
C ++ STL程序,用于检查向量中是否存在给定元素 (C++ STL program to check whether given element exists in the vector or not)
// C++ STL program to check whether given
// element exists in the vector or not
#include <iostream>
#include <vector> // for vectors
#include <algorithm> // for find()
using namespace std;
int main()
{
int element; //element to be searched
// Initializing a vector
vector<int> v1{ 10, 20, 30, 40, 50 };
// input element
cout << "Enter an element to search: ";
cin >> element;
vector<int>::iterator it = find(v1.begin(), v1.end(), element);
if (it != v1.end()) {
cout << "Element " << element << " found at position : ";
cout << it - v1.begin() + 1 << endl;
}
else {
cout << "Element " << element << " does not found" << endl;
}
return 0;
}
Output
输出量
First run:
Enter an element to search: 30
Element 30 found at position : 3
Second run:
Enter an element to search: 60
Element 60 does not found
翻译自: https://www.includehelp.com/stl/check-whether-an-element-exists-in-a-vector-in-cpp-stl.aspx
stl向量