If you are not allowed to sort the vectors then you can use the following approach as it is shown in the demonstrative program below.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector <std::string> animals =
{
"cat", "dog", "pig", "tiger", "monkey", "lion"
};
std::vector <std::string> someAnimals =
{
"dog", "mouse", "snake", "monkey", "cat"
};
auto not_present = [&animals]( const auto &s )
{
return
std::find( std::begin( animals ), std::end( animals ), s ) == std::end( animals );
};
someAnimals.erase( std::remove_if( std::begin( someAnimals ),
std::end( someAnimals ),
not_present ), std::end( someAnimals ) );
for ( const auto &s : someAnimals )
{
std::cout << s << ' ';
}
std::cout << '\n';
return 0;
}
The program output is
dog monkey cat
Otherwise you can use std::binary_search
for the sorted vectors as shown below.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector <std::string> animals =
{
"cat", "dog", "pig", "tiger", "monkey", "lion"
};
std::vector <std::string> someAnimals =
{
"dog", "mouse", "snake", "monkey", "cat"
};
std::sort( std::begin( animals ), std::end( animals ) );
std::sort( std::begin( someAnimals ), std::end( someAnimals ) );
auto not_present = [&animals]( const auto &s )
{
return
not std::binary_search( std::begin( animals ), std::end( animals ), s );
};
someAnimals.erase( std::remove_if( std::begin( someAnimals ),
std::end( someAnimals ),
not_present ), std::end( someAnimals ) );
for ( const auto &s : someAnimals )
{
std::cout << s << ' ';
}
std::cout << '\n';
return 0;
}