I would like to get an iterator of each element in an std::vector
that is also present in a std::map
(as .first
or as a key).
How would I best go about this in an efficient manner?
I would like to get an iterator of each element in an std::vector
that is also present in a std::map
(as .first
or as a key).
How would I best go about this in an efficient manner?
I would do something as follows, which would have a O( N log(n) ) where N = size of vector and n = size of the map. This does not require double loop.
std::vector<int> vec{1,2,3,4,5,6,7,8};
std::map<int, int> myMp{{1,2}, {2,2}, {5,2}, {6,2} };
std::vector<std::vector<int>::iterator> v_itr; // iterators
for(auto itr = vec.begin(); itr != vec.end(); ++itr)
{
auto mp_find = myMp.find(*itr); // log(n) where n = myMp.size()
if(mp_find != myMp.cend()) v_itr.emplace_back(itr);
}