如何从 STL 列表中删除结构记录

How to remove a struct record from an STL list

本文关键字:删除 结构 记录 列表 STL      更新时间:2023-10-16

>我有一个类型为 struct 的列表,我想从该列表中删除特定记录。最好的方法是什么?我不知道如何使用.remove

struct dat
{
    string s;
    int cnt;
};

    void StructList()
    {
        list<dat>::iterator itr; //-- create an iterator of type dat
        dat data1;               //-- create a dat object
        list<dat> dList;         //-- create a list of type dat
        itr = dList.begin();     //-- set the dList itereator to the begining of dList
        string temp;             //-- temp string var for whatever
        data1.s = "Hello";       //-- set the string in the struct dat to "Hello"
        data1.cnt = 1;           //-- set the int in the struct dat to 1
        dList.push_back(data1);  //-- push the current data1 struct onto the dList
        data1.s = "Ted";         //-- set the string in the struct dat to "Ted"
        data1.cnt = 2;           //-- set the int in the struct dat to 2
        dList.push_back(data1);  //-- push the current data1 struct onto the dList
        cout << "Enter Names to be pushed onto the listn";
        for(int i = 0; i < 5; i++)
        {
            cout << "Enter Name ";
            getline(cin,data1.s);   //-- This will allow first and last name
            cout << "Enter ID ";
            cin >> data1.cnt;
            cin.ignore(1000,'n');
            dList.push_back(data1); //-- push this struct onto the list.
        }
// I would like to remove the "Ted, 2" record from the list    
        itr = dList.begin();
        dList.pop_front();       //-- this should pop "Hello" and 1 off the list
        dList.pop_front();       //-- this should pop "Ted" and 2 off the list
        //-- Itereate through the list and output the contents.
        for(itr = dList.begin(); itr != dList.end(); itr++)
        {
            cout << itr->cnt << " " << itr->s << endl;
        }

这是您需要了解的 std::list::remove(( - http://en.cppreference.com/w/cpp/container/list/remove 的参考

如果你有一个类似int的列表,那么remove()就可以了。在您的情况下,尽管您的列表包含一个没有为其定义相等运算符的结构。相等运算符是remove()如何知道传入的参数何时与列表中的参数匹配。注意:这将删除所有匹配的元素,而不仅仅是一个。

带有相等运算符的结构如下所示:

struct dat
{
    string s;
    int cnt;
    bool operator==(const struct dat& a) const
    {
         return ( a.s == this->s && a.cnt == this->cnt )
    }
};

或者,您可以通过迭代器从列表中删除元素。在这种情况下,您将使用 erase() .

这实际上取决于您要做什么以及为什么选择使用std::list。如果您不熟悉这些术语,那么我建议您先阅读更多内容。