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?
It would be something like:
std::erase_if(v, [](const auto& p){ return p.second == "2"; });
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With