对象向量上的 C++ remove_if

时间:2023-05-08
本文介绍了对象向量上的 C++ remove_if的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个对象的向量(顺序很重要)(我们称它们为 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:转换向量&lt;int&gt;串起来 下一篇:使用布尔值向量是否比动态位集慢?

相关文章