Adam Morad
Adam Morad

Reputation: 167

Removing element from vector by member element

Trying to implement a file system I have 3 classes:

  1. BaseFile - Abstract class. Each with a name.
  2. File - Inherits from BaseFile. Each file has a size.
  3. Directory - Inherits from BaseFile. Holds a:

    vector<Base File*> children;
    

I am trying to build a function that deletes a specific file from a directory using a name as a comparable:

for (decltype(children.size()) i = 0; i < children.size(); ++i) {
    if(children[i]->getName() == name) {
        cout << "Same name" << endl;
    }
    else {
        cout << "not found" << endl;
    }
}

I have found the elements are similar but how do i delete the one in the vector?

Upvotes: 0

Views: 46

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93294

You can use the erase-remove_if idiom:

children.erase(
    std::remove_if(
        std::begin(children), 
        std::end(children), 
        [&name](const BaseFile* x){ return x->getName() == name; }
    ),
    std::end(children)
);

Upvotes: 3

Related Questions