如何从 STL 列表中删除结构记录
How to remove a struct record from an STL list
>我有一个类型为 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。如果您不熟悉这些术语,那么我建议您先阅读更多内容。
相关文章:
- 如何在cpp中删除(免费)多维结构内存?
- 从函数中全局删除并重新实例化数组结构,而无需在编译时知道数组的大小
- 从向量中删除结构,解构它
- shared_ptr删除结构内的对象
- 如何从 STL 列表中删除结构记录
- 程序在删除结构中的指针数组时崩溃
- 删除C结构末尾填充的最佳做法是什么
- 如何安全地删除结构
- 如何在不知道其类型的情况下删除结构
- 删除结构的成员,并将其重新制作为其他内容的副本,而不使用 new
- 删除结构的指针是否也会删除结构中的指针?
- 从C++中的二进制文件中删除结构
- 删除结构c++的向量中的重复项
- 删除结构数组,更改结构地址
- 在c++中从文件中删除结构
- 使用delete运算符删除结构中的元素
- VS 2010 C++在删除结构数组时崩溃
- 如何删除结构数组的元素
- 需要删除动态结构内容,然后删除结构本身
- 使用迭代器从STL列表中删除c++结构