C++ remove_if on a vector of objects(对象向量上的 C++ remove_if)
问题描述
我有一个对象的向量(顺序很重要)(我们称它们为 myobj 类),我试图一次删除多个对象.
I have a vector (order is important) of objects (lets call them myobj class) where I'm trying to delete multiple objects at a time.
class vectorList
{
vector<*myobj> myList;
};
class myobj
{
char* myName;
int index;
bool m_bMarkedDelete;
}
我认为最好的方法是标记要删除的特定 myobj 对象,然后在向量上调用 myList.remove_if().但是,我不确定如何为此使用谓词等.我应该在对象中创建一个成员变量,让我说我想删除 myobj 然后创建一个谓词来检查是否设置了成员变量?
I was thinking that the best way to do this would be to mark specific myobj objects for deletion and then call myList.remove_if() on the vector. However, I'm not exactly sure how to use predicates and such for this. Should I create a member variable in the object which allows me to say that I want to delete the myobj and then create a predicate which checks to see if the member variable was set?
如何将谓词实现为 vectorList 类的一部分?
How do I implement the predicate as a part of the vectorList class?
推荐答案
我应该在对象中创建一个允许我说的成员变量吗我想删除 myobj 然后创建一个谓词检查成员变量是否设置?
Should I create a member variable in the object which allows me to say that I want to delete the myobj and then create a predicate which checks to see if the member variable was set?
你不是已经这样做了吗?这不是 m_bMarkedDelete
的用途吗?你可以这样写谓词:
Haven't you already done that? Isn't that what m_bMarkedDelete
is for? You would write the predicate like this:
bool IsMarkedToDelete(const myobj & o)
{
return o.m_bMarkedDelete;
}
那么:
myList.erase(
std::remove_if(myList.begin(), myList.end(), IsMarkedToDelete),
myList.end());
或者,使用 lambda:
Or, using lambdas:
myList.erase(
std::remove_if(myList.begin(), myList.end(),
[](const myobj & o) { return o.m_bMarkedDelete; }),
myList.end());
如果你的班级实际上没有那个成员,而你问我们是否应该有,那么我会说没有.您使用什么标准来决定将其标记为删除?在谓词中使用相同的条件,例如:
If your class doesn't actually have that member, and you're asking us if it should, then I would say no. What criteria did you use to decide to mark it for deletion? Use that same criteria in your predicate, for example:
bool IndexGreaterThanTen(const myobj & o)
{
return o.index > 10;
}
note -- 我写的函数当然是无效的,因为你所有的成员都是私有的.因此,您需要某种方式来访问它们.
note -- The functions I've written are of course invalid since all your members are private. So you'll need some way to access them.
这篇关于对象向量上的 C++ remove_if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:对象向量上的 C++ remove_if
基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01