Home > Enterprise >  Using erase - is there a way to make this code less repetitive?
Using erase - is there a way to make this code less repetitive?

Time:01-07

This code deletes six lines from a file about a person from a contact list. This code works perfectly fine, however I don't know how to make this code less repetitive.

I use a while loop to push my lines inside a vector, and then use the following for loop to erase from the vector. At the end of the loop, I recreate the file again and push the remaining data into the file.

As you can see, I repeat file.erase() many times.

std::cout << "Enter name of contact you would like to delete: ";
getline(std::cin, search); 

for(int i = 0; i < (int)file.size();   i)
{
    if(file[i].substr(0, search.length()) == search) 
    {                   
        file.erase(file.begin()   i); 
        file.erase(file.begin()   i); 
        file.erase(file.begin()   i);
        file.erase(file.begin()   i); 
        file.erase(file.begin()   i); 
        file.erase(file.begin()   i); 
        std::cout << "Success, contact deleted!"<< std::endl;
        i = 0; 
    } 
}

Could I use the following code to manufacture my code in a better, less repetitive, way?

for(int remaining = 6; remaining > 0 && itr != file.end(); itr  , remaining--) {

CodePudding user response:

Instead of erasing the first element for 6 times, you can do:

file.erase(file.begin()   i, file.begin()   i   6)

The two args in this erase method denotes the range [first, last) to erase. Reference link

  •  Tags:  
  • Related