簡體   English   中英

從std :: list中刪除std :: tuple

[英]Removing std::tuple from std::list

我有一個元組列表,需要從列表中刪除元素,如下所示:

enum class test
{
    mem1,
    mem2,
    mem3,
    mem4
};

struct A
{

};

int main()
{
    std::list<std::tuple<int, test, A>> tuple_list;

    // fill list with random objects
    for (int i = 0; i < 4; i++)
    {
        tuple_list.push_back(
               std::forward_as_tuple(i, static_cast<test>(i), A()));
    }

    // now remove it
    for (auto& ref : tuple_list)
    {
        tuple_list.remove(ref); // error C2678
    }
    return 0;
}

錯誤C2678:二進制'==':找不到哪個運算符帶有'const _Ty'類型的左操作數(或者沒有可接受的轉換)

如何從上面的示例中的列表中刪除元組元素?

編輯:

我嘗試了以下方法,它編譯得很好,不像以前的例子,但有運行時斷言:

int main()
{
    list<tuple<int, test, A>> tuple_list;

    for (int i = 0; i < 4; i++)
    {
        tuple_list.push_back(
                std::forward_as_tuple(i, static_cast<test>(i), A()));
    }

    for (auto iter = tuple_list.begin(); iter != tuple_list.end(); iter++)
    {
        tuple_list.erase(iter);
    }
}

表達式:無法遞增值初始化列表迭代器

首先, 你不想這樣做 從刪除的項目list中的中間(或任何容器)范圍為基礎for是一個災難的背后隱藏着for循環是迭代器 ,將盡快項被刪除無效。

這與第二次實驗的問題相同

for (auto iter = tuple_list.begin(); iter != tuple_list.end(); iter++)
{
    tuple_list.erase(iter); // iter rendered invalid. 
                            // That makes iter++ and iter != tuple_list.end()
                            // totally bogus.
}

這個版本可以修復

for (auto iter = tuple_list.begin(); iter != tuple_list.end(); /* nothing here */)
{
    iter = tuple_list.erase(iter); // iter updated here
}

或者a

while (! tuple_list.empty()) 
{
     tuple_list.pop_front();
}

要么

tuple_list.clear();

好。 到底出了什么問題:

錯誤C2678:二進制'==':找不到哪個運算符帶有'const _Ty'類型的左操作數(或者沒有可接受的轉換)

表示無法比較元組的其中一個部分是否相等。

struct A
{

};

沒有相等的運算符。 解決方案是添加一個。

struct A
{
}; 

bool operator==(const A& lhs, const A& rhs)
{ 
    Comparison logic goes here 
}    

有用的額外閱讀:

擦除刪除成語可用於解決類似問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM