[英]How to remove an item from a list of tuples in c++?
我正在遍历我的元组列表: list<tuple<int,int>> edges
,并希望删除其中的一些元素。 当我处理大量数据时,这对于减少总开销是必要的。
std::list<tuple<int, int>>::iterator it;
for (it = edges.begin(); it != edges.end(); ++it)
{
if (get<0>(*it) == 0 || get<1>(*it) == 0){
edges.remove(*it);
}
}
据我所知, remove(element)
有效,但这里edges.remove(*it)
无效。 我怎样才能正确地做到这一点?
您可以使用erase()
指定要由迭代器删除的元素。
它为下一个元素返回一个迭代器,所以不要忘记抓住它。
std::list<tuple<int, int>>::iterator it;
for (it = edges.begin(); it != edges.end(); ) // don't increment it here
{
if (get<0>(*it) == 0 || get<1>(*it) == 0){
it = edges.erase(it);
} else {
++it;
}
}
在 C++20 中,您可以简单地使用std::erase_if
的特殊化 for std::list
来执行此操作。
#include <list>
#include <tuple>
int main() {
std::list<std::tuple<int, int>> l;
std::erase_if(l, [](const auto& elem) {
auto& [first, second] = elem;
return first == 0 || second == 0; });
}
但是,由于std::list
本身有一个remove_if
成员 function,因此直接使用它更合适,因为它适用于任何 C++ 标准。
在我的观点中, remove_if
是一个专用和优化的 function ,应该使用std::list
。 这将避免不必要的间接。
请在此处阅读。
结果将是一个高效的单班轮。
请查看众多潜在解决方案之一:
#include <iostream>
#include <list>
#include <tuple>
using MyTuple = std::tuple<int,int>;
using MyList = std::list<MyTuple>;
int main() {
// Define some demo data
MyList myList{{0,1},{2,3},{4,5},{6,0},{7,8},{9,10},{0,0}};
// Predicate function. Define whatever you want
auto unwanted = [](const MyTuple& t) {return std::get<0>(t)==0 or std::get<1>(t)==0;};
// Remove all unwanted stuff
myList.remove_if(unwanted);
// Some debug output
for (const auto&[l,r] : myList)
std::cout << l << ' ' << r << '\n';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.