2017-04-14 2 views
-1

私はstructタイプのリストを持っており、そのリストから特定のレコードを削除したいとします。これを行う最善の方法は何ですか?私は、これはあなたがのstd ::リストについて理解する必要が参照され.removeSTLリストから構造レコードを削除する方法

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 list\n"; 
     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; 
     } 
+0

あなたはそのコードで 'remove'を使用していませんか? – user463035818

+1

'std :: list :: remove_if'を参照してください。http://en.cppreference.com/w/cpp/container/list/remove –

+0

@ tobi303、私はそれを動作させることができなかったので、私はそれを引っ張った。 – dmaelect

答えて

1

でそれを行う方法を見つけ出すことはできません::()削除 - http://en.cppreference.com/w/cpp/container/list/remove

あなたはintのようなもののリストを持っていた場合ちょうどremove()が機能します。あなたのケースでは、あなたのリストに等価演算子が定義されていない構造体が含まれています。等価演算子は、渡されたパラメータがリストにあるものと一致するときをどのようにしてremove()が知るかです。注:これは、1つではなく、一致するすべての要素を削除します。

等価演算子を使って構造体は次のようなものに見えるでしょう:

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を使用することにしたのかによって異なります。 これらの用語に精通していない場合は、まず最初に読むことをお勧めします。

+0

'operator =='は 'const'でなければなりません。より良い、それを自由な機能にする。 – aschepler

+0

うん、本当。わかった – MrJLP

関連する問題