-4

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?

JeJo
  • 30,635
  • 6
  • 49
  • 88
stdcerr
  • 13,725
  • 25
  • 71
  • 128
  • What have you done so far? – JeJo Jun 21 '18 at 16:42
  • @jejo read documentation and been wondering if iteration over my map in combination with `std::find()` is the most efficient way to solve this as it ultimately equals a "double loop" and it could be quite time consuming depending on the number of elements in either container... – stdcerr Jun 21 '18 at 16:48
  • are you looking for the *iterator of each element in a std::vector* or the *element* itself? if so you can do other way around. For each element of the vector find in std::map. However, I recomment you do show your research in your qestion, otherwise it will be closed. – JeJo Jun 21 '18 at 16:52
  • Do you want to test if the vector element is a key in the map or a value in the map? – Barmar Jun 21 '18 at 17:07
  • If you're looking for keys, iterate over the vector and test whether the element is in the map, you don't need a double loop. – Barmar Jun 21 '18 at 17:08

1 Answers1

1

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);
   }
JeJo
  • 30,635
  • 6
  • 49
  • 88