C++对象向量上的remove_if
我有一个对象向量(顺序很重要)(我们称它们为 myobj 类),我试图一次删除多个对象。
class vectorList
{
vector<*myobj> myList;
};
class myobj
{
char* myName;
int index;
bool m_bMarkedDelete;
}
我认为最好的方法是标记特定的 myobj 对象以进行删除,然后在向量上调用 myList.remove_if() 。但是,我不太确定如何使用谓词等。我是否应该在对象中创建一个成员变量,它允许我说我想要删除 myobj,然后创建一个谓词来检查成员变量是否已设置?
如何将谓词实现为 vectorList 类的一部分?
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;
}
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?
How do I implement the predicate as a part of the vectorList class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不是已经这样做了吗?这不是
m_bMarkedDelete
的用途吗?您可以这样编写谓词:然后:
或者,使用 lambda:
如果您的类实际上没有该成员,而您问我们是否应该有该成员,那么我会说不。您根据什么标准决定将其标记为删除?在谓词中使用相同的条件,例如:
注意 -- 我编写的函数当然是无效的,因为您的所有成员都是私有的。因此,您需要某种方式来访问它们。
Haven't you already done that? Isn't that what
m_bMarkedDelete
is for? You would write the predicate like this:Then:
Or, using lambdas:
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:
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++ lambda 的示例。此代码将遍历向量并删除等于 3 的值。
编辑: 对于指针,假设您有一个向量或接口,您可以将它们设置为
nullptr
然后删除它们在一批中具有几乎相同的代码。在 VS2008 中,您不会有 lambda,因此请创建一个比较谓词函数或结构体。A predicate is basically a conditional comparison. It can be a function or object. Here's an example using new C++ lambdas. This code will go through the vector and remove the values equal to 3.
Edit: For pointers let's say you had a vector or interfaces you could set them to
nullptr
then remove them in a batch with pretty much the same code. In VS2008 you won't have lambdas so make a comparison predicate function or struct instead.