OneBite.Dev - Coding blog in a bite size

Insert An Element At The Beginning Of An Array In C++

Code snippet for how to Insert An Element At The Beginning Of An Array In C++ with sample and detail explanation

Inserting an element at the beginning of an array is a common task in programming. This article will outline a simple and easy to understand method, using C++, to perform this function.

Code Snippet for Inserting an Element at the Beginning of an Array

#include<iostream>
#include<vector>

using namespace std;

int main(){
  vector<int> vec {10, 20, 30, 40, 50};

  vec.insert(vec.begin(), 0);

  for(int i = 0; i < vec.size(); i++)
    cout << vec[i] << " ";
  
  return 0;
}

Code Explanation for Inserting an Element at the Beginning of an Array

In the code snippet above, we follow the specific steps to insert an element at the beginning of an array in C++.

First, we include the necessary headers by calling the iostream and the vector libraries. These are included by using the #include directive. The iostream library is standard for reading and writing from the console, and the vector library allows us to work with vector objects.

The using namespace std; statement allows us to use elements in the standard library (such as vectors and cout) without prefacing them with β€˜std::β€˜.

Within the main function, we define a vector vec of integers using the braces {}. Vectors are much like C++ arrays, but have the added advantage of dynamic sizes.

Next, we use the insert() function from the vector library to add a new element at the beginning of the vector. The vec.begin() function returns an iterator pointing to the first element in the vector. Hence, vec.insert(vec.begin(), 0); inserts the integer 0 at the start of the vector.

Finally, the for loop is used to print the contents of the vector to the console. vec.size() gives the size of the vector. So, the loop starts with i as 0 and continues until i is less than the size of the vector. For each iteration, it prints the value of the ith index of the vector followed by a space.

We then return 0 to signal the successful execution of the program. Running this code, your console should display β€œ0 10 20 30 40 50”, showing that the number 0 has been successfully inserted at the start of the array.

c-plus-plus