Monday, February 5, 2018

c++ - How to find out if an item is present in a std::vector?

(C++17 and above):




can use std::search also



This is also useful for searching sequence of elements.



#include 
#include
#include

template
bool search_vector(const Container& vec, const Container& searchvec)

{
return std::search(vec.begin(), vec.end(), searchvec.begin(), searchvec.end()) != vec.end();
}

int main()
{
std::vector v = {2,4,6,8};

//THIS WORKS. SEARCHING ONLY ONE ELEMENT.
std::vector searchVector1 = {2};

if(search_vector(v,searchVector1))
std::cout<<"searchVector1 found"< else
std::cout<<"searchVector1 not found"<
//THIS WORKS, AS THE ELEMENTS ARE SEQUENTIAL.
std::vector searchVector2 = {6,8};
if(search_vector(v,searchVector2))
std::cout<<"searchVector2 found"< else

std::cout<<"searchVector2 not found"<
//THIS WILL NOT WORK, AS THE ELEMENTS ARE NOT SEQUENTIAL.
std::vector searchVector3 = {8,6};
if(search_vector(v,searchVector3))
std::cout<<"searchVector3 found"< else
std::cout<<"searchVector3 not found"<}



Also there is flexibility of passing some search algorithms. Refer here.



https://en.cppreference.com/w/cpp/algorithm/search

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...