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向量