Monday, 5 February 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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...