gpt-4-0314· openai
Suzhen/CodeChat
如何删去QList<QAction*>中所有名为“24V”的QAction,通过{}这样的lamba表达式
- User
- Assistant
使用
std::remove_if结合lambda表达式实现如下:#include <QList> #include <QAction> #include <algorithm> // Example QList of QAction pointers QList<QAction*> actionList; actionList.push_back(new QAction("24V")); actionList.push_back(new QAction("12V")); actionList.push_back(new QAction("24V")); actionList.erase( std::remove_if(actionList.begin(), actionList.end(), [](QAction* action) { bool shouldRemove = (action->text() == "24V"); if (shouldRemove) { delete action; } return shouldRemove; }), actionList.end());这里使用了
std::remove_if来删除QList中所有名为 "24V" 的QAction。我们传递一个 lambda 函数作为删除条件,将QAction文本与 "24V" 进行比较。在移除QAction之前,我们需要释放QAction指针所指向的内存,否则会造成内存泄漏。