[英]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.