How to remove elements from a vector inside a loop in C++

Hello, Coders! In this section, we will learn and discuss the vector and how to remove elements from a vector inside a loo in C++.

Let’s cover up the following topics briefly;

  • Vector in C++

Vectors in C++

  • The Vectors are containers that contain sequence. It represents arrays that can change in size, in other words, we can say vectors same as a dynamic array. When the element is got inserted or deleted, the storage is being handled automatically by the vector.
  • The elements can be accessed using regular pointers, as the vectors use contiguous memory locations to store the elements.
  • Vector containers are capable of assigning more memory for the possible growth of the elements, so the vector containers have greater actual capacity than the storage needed to contain the elements.
  • It is more efficient as compared to deques and lists in terms of efficient accessing of the elements.

Syntax:

vector<data_type> var = {....};

Program to remove elements from a vector inside a loop in C++

  • In this program, we will use iterators to iterate the vector and call the vector::erase function when the current element match with the possible element.
#include <iostream>
#include <vector>
#include <algorithm>
 
 using namespace std;
 
int main()
{
   vector<int> vec = { 78, 69, 75, 105, 86, 15 };
 
    auto a = vec.begin(); //begin() returns iterator pointing to the first element
    while (a != vec.end()) //end() returns iterator pointing to the last element
    {
        // Condition for removing the odd numbers
        if (*a & 1)
        {
    
            a = vec.erase(a); //erase() is used to remove elements from a container
        }
        
        else {
            ++a;
        }
    }
 
    for (int const &i: vec) {
         cout << i << ' ';
    }
 
    return 0;
}
  • Here, we use the erase() function return value to set the iterator to the next element.

Output:

78 86

Hope this article has helped you understand the concept of vectors and remove the elements from the vector in a loop in c++.

Happy coding!!!

You can also read, Take user input into a vector in C++

Leave a Reply

Your email address will not be published. Required fields are marked *