簡體   English   中英

從類型結構列表中刪除元素

[英]Erase element from list of type struct

這是我的列表的聲明: list<Message*> g_messages;

其中Message是一個struct

我想刪除列表的某個位置(消息)。 如果它是一個向量,我會這樣做:

//delete g_messages[id];

列表.erase()必須使用,但我不知道如何。

g_messages.erase(id); 不起作用。 有人建議使用迭代器,但是如何鏈接const int id和迭代器?

這就是你如何使用列表,你必須遍歷所有這些,因為它們是雙鏈表(每個元素都包含指向前一個和下一個元素的指針)。

// loop through all the elements
for (auto& it = g_messages.begin(); it != g_messages.end(); it++)
{
    if ((*it)->id == input_id)
    {
        delete *it;
        g_messages.erase(it);
        break;
    }
}

另一個選擇是使用來自<algorithm> std :: find_if,它接受一個謂詞

auto it = std::find_if(g_messages.begin(), g_messages.end(), [input_id](Message* p){ return (p->id == input_id); });

if (it != g_messages.end())
{
    delete *it;
    g_messages.erase(it);
}

編輯:按照OP的要求(刪除它相對於開始的位置)

// loop through all the elements
int i = -1;
for (auto& it = g_messages.begin(); it != g_messages.end(); it++)
{
    if (++i == input_position)
    {
        delete *it;
        g_messages.erase(it);
        break;
    }
}

要么

auto it = g_messages.begin();

if (input_position < g_messages.size())
{
    std::advance(it, input_position);
    g_messages.erase(it);
}

要清除list<Message*>的元素,您必須做三件事:

  • 得到一個指向你想要擺脫的元素的迭代器。 遺憾的是, 列表迭代器是雙向的 :您可以轉到列表的開頭或結尾,一次向前/向后移動一個步驟。
  • 刪除你指向的對象(順便說一下,在這里使用智能指針而不是原始指針會更安全:你可以跳過這個額外的步驟並確保你沒有泄漏內存)
  • 擦除列表的元素

在這里怎么做:

auto it = g_messages.begin();   // iterator to start at begin of list 
it++;it++;              // move two steps forward (i.e. 2x  1 step)
delete *it;             // delete the allocated object you point to 
g_messages.erase(it);   // erase the elemnt in the list.  

這是一個使用智能指針的快速現場演示

暫無
暫無

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

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