[英]How do you remove all pairs from a vector of pairs that have a certain value as their first value
Let's say the pairs I wanted to remove would have 2 as their first value.假设我想删除的对的第一个值是 2。
A vector like this:像这样的向量:
vector<pair<int,int>> v = {{1,2}, {2,3} , {2,4} , {5,4}};
would become after the removal of pairs:删除对后会变成:
v = {{1,2}, {5,4}}
How would I do this?我该怎么做? Is it some implementation of the erase-remove idiom?
它是擦除-删除习语的某种实现吗? Because I don't know how it should check the first value in the pair.
因为我不知道它应该如何检查该对中的第一个值。
The standard library has remove_if to do this :标准库有 remove_if 来做到这一点:
#include <algorithm>
#include <iostream>
#include <vector>
#include <utility>
int main()
{
std::vector<std::pair<int, int>> v = { {1,2}, {2,3} , {2,4} , {5,4} };
// use std::remove_if
// this will move al elements to erase to the end of the vector so you can erase them after
// https://en.cppreference.com/w/cpp/algorithm/remove
// the 3d argument is a lambda (you can also use a function)
// https://en.cppreference.com/w/cpp/language/lambda
auto removed_it = std::remove_if(v.begin(), v.end(), [](const std::pair<int, int>& pair)
{
// return true if the first value of the pair is 2.
return pair.first == 2;
});
// cleanup the vector
v.erase(removed_it, v.end());
// show the cleaned up content
for (const auto& pair : v)
{
std::cout << pair.first << ", " << pair.second << "\n";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.