Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erase element by value from vector of pairs

Tags:

c++

vector

c++20

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?

like image 469
Arne Avatar asked Aug 01 '19 09:08

Arne


1 Answers

It would be something like:

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

Demo

like image 60
Jarod42 Avatar answered Nov 15 '22 01:11

Jarod42