vendredi 5 août 2022

Properly implement erasing from vector

ALL,

I have a following structure

struct Definition
{
    std::string schema, name;
    Definition(const std::string &s, const std::string n) : schema(s), name(n) {}
}

and I have a following class

class Foo
{
public:
    Foo()
    {
        myVector.push_back( "abc", "def" );
        myVector.push_back( "abc", "ghi" );
        myVector.push_back( "abc", "jkl" );
    }
    void EditVector();
private:
    std::vector<Definition> myVector;
};

void Foo::EditVector()
{
    for( auto i = 0; i < somedata.size(); ++i )
    {
        // if somedata[i] is not found inside mtVector name - add it
        // if somedata.size() is less than myVector - remove the extra element
    }
}

Now adding the element not found is easy - just do find_if() and if it returns myVector.end() - call push_back().

But what about removing?

I thought I can save myVector to a temporary one, then remove the element from that temporary and finally remove elements from myVector that are left inside the temporary one. But how do I do that? Or maybe there is a better and more elegant solution?

The somedata is a dynamic vector and its content is not known at the time.

TIA!!

I did see the answer here but it uses simple/basic type. And maybe there is even more elegant soltion

Aucun commentaire:

Enregistrer un commentaire