【发布时间】:2017-04-14 21:59:35
【问题描述】:
我有一个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 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;
}
【问题讨论】:
-
您没有在该代码中使用
remove,是吗? -
见
std::list::remove_ifen.cppreference.com/w/cpp/container/list/remove -
@tobi303,我拉它是因为我无法让它工作。
-
"// 出于某种原因这不起作用 // dList.sort();" -- 谁告诉你你可以期待“dlist.sort();”去工作? C++ 从来没有这样工作过。这听起来像是来自一个移植的 Java 开发人员,他认为仅仅因为这是你在 Java 中对向量或列表进行排序的方式,它必须是在 C++ 中完成的方式。好吧,C++ 不是这样工作的。如果您了解 Java 并且正在尝试学习 C++,那么最好的方法是阅读您的 C++ 书籍,而不是猜测如何在 C++ 中做一些您知道如何在 Java 中做的事情。
-
@SamVarshavchik,为了清楚起见,我有一本书,正在阅读。它有一个
<int> list的小例子。所以我想我会看到它如何与struct数据类型一起工作,因此进行了实验。也许我应该说练习。无论哪种方式,您的输入都是有帮助的,但现在我们偏离了原始问题的主题,即如何删除上述示例中的特定记录。我不是想让它做一些不可能的事情,我是在努力学习和理解它。