(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.
No comments:
Post a Comment