Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove a Chunk of Items from a Vector?

I have a vector full of words and I am trying to erase a chunk of that vector at a specified beginning and end. For example:

#include <string>
#include <vector>

int main() {
    std::vector<std::string> words = { "The", "Quick", "Brown", "Fox", "Jumps", "Over", "The", "Lazy", "Dog" };
    remove_chunk(words, 1, 2);
}

Here, remove_chunk(words, 1, 2); would erase the items at index 1 through 2, leaving the vector to be:

{ "The", "Fox", "Jumps", "Over", "The", "Lazy", "Dog" }

How would I go about efficiently writing remove_chunk? Is there an stl function for this or a quick one-liner?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use vector::erase:

words.erase(words.begin(), words.begin() + 2);

Note: Second iterator provided is words.begin() + 2 instead of words.begin() + 1 because STL uses [begin, end).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading