简体   繁体   中英

How to delete a repetead value in a multimap c++?

I have a multimap filled with these elements (key, value):

PROJECTONE,asdsa

PROJECTTWO,asdsa

PROJECTTHREE,hello

PROJECTFOUR,asdsa

I want to delete all the elements of the multimap with the same value, it doesn´t matter if the key is different as you see in the example. In this example, i need to delete projectone, projecttwo and projectfour because they have the same value (asdsa).. so the output when i print the multimap is only:

PROJECTTHREE,hello

A iterative approach like this can solve your problem.

std::unordered_set<string> s; // to track the values seen so far.
for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{

  if (s.find(it->second) != s.end())
  {
    m.erase(it++);    // or "it = m.erase(it)" since C++11
  }
  else
  {
    s.emplace(it->second);
    ++it;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM