Is there a function in C ++ that determines whether there is a given element in the vector?
3 answers
Such tasks are solved using standard algorithms declared in the <algorithm>, header <algorithm>, such as
std::find std::find_if std::find_if_not std::find_end std::find_first_of std::adjacent_find std::search std::search_n If the vector is sorted, then you can also use binary-based algorithms, such as
std::binary_search std::lower_bound std::upper_bound std::equal_range Here is the simplest demonstration program.
#include <iostream> #include <algorithm> #include <cstdlib> #include <ctime> #include <vector> int main() { const int N = 10; std::vector<int> v( N ); std::srand( ( unsigned int )std::time( nullptr ) ); std::generate( v.begin(), v.end(), [=] { return std::rand() % N; } ); for ( int x : v ) std::cout << x << ' '; std::cout << std::endl; for ( int i = 0; i < N; i++ ) { if ( std::find( v.begin(), v.end(), i ) != v.end() ) { std::cout << i << " is present in the vector" << std::endl; } else { std::cout << i << " is not present in the vector" << std::endl; } } std::cout << std::endl; std::sort( v.begin(), v.end() ); for ( int x : v ) std::cout << x << ' '; std::cout << std::endl; for ( int i = 0; i < N; i++ ) { if ( std::binary_search( v.begin(), v.end(), i ) ) { std::cout << i << " is present in the vector" << std::endl; } else { std::cout << i << " is not present in the vector" << std::endl; } } std::cout << std::endl; return 0; } Its output to the console might look like this:
6 1 4 6 2 6 6 2 6 7 0 is not present in the vector 1 is present in the vector 2 is present in the vector 3 is not present in the vector 4 is present in the vector 5 is not present in the vector 6 is present in the vector 7 is present in the vector 8 is not present in the vector 9 is not present in the vector 1 2 2 4 6 6 6 6 6 7 0 is not present in the vector 1 is present in the vector 2 is present in the vector 3 is not present in the vector 4 is present in the vector 5 is not present in the vector 6 is present in the vector 7 is present in the vector 8 is not present in the vector 9 is not present in the vector |
But what about? find or find_if .
if (find(v.begin(),v.end(),val) != v.end()) ... |
template<class T> bool contains(const std::vector<T>& arr, const T& value) { return std::cend(arr) != std::find(cbegin(arr), cend(arr), value); } |