Arne
Arne

Reputation: 1338

Erase element by value from vector of pairs

Since C++20, we can erase an element by value from a vector by doing, for example:

std::vector<int> v = {10,20,30,40,50};
std::erase(v,30);

That's really convenient and all not to mention there's also std::erase_if.

However, what if we have a vector of pairs and we want to erase, only if the second value of the pair matches?

std::pair<int, std::string> foo = std::make_pair(1,"1");
std::pair<int, std::string> foo2 = std::make_pair(2,"2");

std::vector< std::pair<int, std::string> > v;
v.push_back(foo);
v.push_back(foo2);

std::erase(v, make_pair(1,"2"));    //This is not going to work!

So, is there a way to erase the element by the second value from a vector of pairs?

Upvotes: 6

Views: 370

Answers (1)

Jarod42
Jarod42

Reputation: 217810

It would be something like:

std::erase_if(v, [](const auto& p){ return p.second == "2"; });

Demo

Upvotes: 3

Related Questions