Ins*_*Now 0 c++ vector std-pair
假设我想要删除的对的第一个值是 2。
像这样的向量:
vector<pair<int,int>> v = {{1,2}, {2,3} , {2,4} , {5,4}};
Run Code Online (Sandbox Code Playgroud)
删除对后将变为:
v = {{1,2}, {5,4}}
Run Code Online (Sandbox Code Playgroud)
我该怎么做?它是擦除删除惯用语的某种实现吗?因为我不知道它应该如何检查该对中的第一个值。
标准库有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";
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
299 次 |
最近记录: |