Arrays are one of the most commonly used data structures in C++. They allow you to store multiple values of the same data type in contiguous memory locations.

Once an array is declared, its size is fixed and cannot be changed. So a common requirement is to add a new element to an existing array. There are a few different techniques to accomplish this in C++. In this comprehensive guide, we will explore the main methods to add elements to C++ arrays with sample code examples.

1. Create a New Bigger Array

One straightforward approach is to:

  1. Create a new array with bigger size
  2. Copy existing array elements into it
  3. Add the new element

Here is how it works:

#include <iostream>
using namespace std;

int main() {

  // Existing array
  int arr[5] = {10, 20, 30, 40, 50};

  // New element to add
  int x = 60;

  // Create new bigger array
  int newArr[6];

  // Copy existing array elements
  for(int i = 0; i < 5; i++) {
    newArr[i] = arr[i]; 
  }

  // Add new element    
  newArr[5] = x;

  // Print new array
  for(int i = 0; i < 6; i++) {
    cout << newArr[i] << " "; 
  }

  return 0;
}

This prints:

10 20 30 40 50 60

The key steps are:

  1. Define a new array with bigger size
  2. Copy existing array into new array
  3. Assign new element to new array

The main downside is that you need to manually copy contents from old to new array.

Now let‘s explore some better methods.

2. Create a Dynamic Array using Vectors

Vectors are sequence containers that provide dynamic arrays in C++. The size of a vector can grow and shrink dynamically as elements are added or removed.

Here is how to add an element to a vector:

#include <iostream> 
#include <vector>
using namespace std;

int main() {

  // Create a vector
  vector<int> vec {10, 20, 30, 40, 50}; 

  // Add new element
  int x = 60;
  vec.push_back(x);

  // Print vector
  for(int i=0; i<vec.size(); i++) {
    cout << vec[i] << " "; 
  }

  return 0;
}

This dynamically adds the new element 60 to the vector and prints:

10 20 30 40 50 60

Using vectors avoids the effort of manually creating a new bigger array and copying elements.

Some key points about C++ vectors:

  • Automatically expand as you add elements
  • Access elements using index (square brackets)
  • Use push_back() method to add new element at end
  • size() gives current size
  • More flexible than simple arrays

So vectors provide an easier way to add elements dynamically.

3. Create Array on Heap using new Operator

We can also create arrays dynamically on the heap using the new operator in C++. Here is the syntax:

dataType* arrayPtr = new dataType[size];

This allocates an array of given data type and size on the heap, and arrayPtr points to the first element of this array.

To add a new element, we can:

  1. Create a new bigger array on heap
  2. Copy contents from old array
  3. Add new element
  4. Delete old array

Here is how it works:

#include <iostream>
using namespace std;

int main() {

  // Existing array on heap
  int* arr = new int[5] {10, 20, 30, 40, 50};

  // New element 
  int x = 60; 

  // Create new bigger array
  int* newArr = new int[6];

  // Copy values from old array 
  for(int i = 0; i < 5; i++) {
    newArr[i] = arr[i];
  }

  // Add the new element
  newArr[5] = x; 

  // Print new array   
  for(int i = 0; i < 6; i++) {
    cout << newArr[i] << " "; 
  }

  // Delete arrays
  delete [] arr;
  delete [] newArr;

  return 0;
}

This prints:

10 20 30 40 50 60

The key steps are:

  1. Create new array using new operator
  2. Copy elements from old array
  3. Add new element at end
  4. Delete old and new arrays (to avoid memory leaks)

The advantage over regular arrays is that new array can be created dynamically on the heap at runtime.

However, an easier way is to use vectors (as seen before) which handle most of these steps automatically.

4. Insert Element in Middle of Array

All previous methods focused on adding the element at the end of the array.

To insert an element in the middle of the array, we need to:

  1. Create space for new element by shifting existing ones
  2. Insert new element in this space

Here is an example:

#include <iostream>
using namespace std;

int main() {

  int arr[100] = {0}; 
  int size = 6, element = 60, pos = 3;

  // Initial array  
  for(int i = 0; i<size; i++) {
    arr[i] = i * 10; 
  }

  // Find position  
  int newPos = pos - 1;

  cout << "Before Insertion: ";
  // Print elements  
  for(int i = 0; i<size; i++) {
    cout << arr[i] << " ";
  }

  // Shift elements forward
  for(int i = size-1; i >= newPos; i--) {
    arr[i+1] = arr[i];
  }

  // Insert element
  arr[newPos] = element;

  size++;

  cout << "\nAfter Insertion: ";

  // Print array after insertion 
  for(int i = 0; i<size; i++) {
    cout << arr[i] << " "; 
  }

  return 0;  
}

This shifts the array elements from pos onwards to create space for new element 60 at pos 3 and prints:

Before Insertion: 0 10 20 30 40 50
After Insertion: 0 10 20 60 30 40 50  

The algorithm is:

  1. Compute index to insert (pos – 1)
  2. Shift elements from this index onwards
  3. Insert element at index
  4. Increment array size

We manually have to shift elements and cannot insert elements directly.

The insertion operation takes linear time O(n).

This method works for normal arrays but for vectors, we can use the insert() method instead.

5. Insert into Vector using insert()

C++ vectors provide an insert() method to insert one or more elements at a given position:

vector_name.insert(pos, element); 

Here, pos is the position and element is the element to insert.

For example:

#include <iostream>
#include <vector>
using namespace std;

int main() {

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

  // Element to insert  
  int x = 15;

  // Position 
  int pos = 1;

  cout << "Vector Before Insertion: ";
  for(int i=0; i<vec.size(); i++) {
    cout << vec[i] << " ";
  }

  // Insert 15 at position 1
  vec.insert(pos, x);

  cout << "\nVector After Insertion: ";
  for(int i=0; i<vec.size(); i++) {
    cout << vec[i] << " ";
  }

  return 0;  
}

This inserts 15 at index 1 and prints:

Vector Before Insertion: 10 20 30 40 50
Vector After Insertion: 10 15 20 30 40 50

The steps are:

  • Specify position to insert
  • Call insert() and pass element and position

Much simpler than manually shifting array elements!

Vectors also provide an insert() version to insert from another array which is very useful.

6. Insert Contents of One Vector into Another

We can insert all elements from one vector into another using:

targetVector.insert(targetVector.begin() + pos, sourceVector.begin(), sourceVector.end());

This inserts contents of sourceVector into targetVector starting from position pos.

For example:

#include <iostream> 
#include <vector>
using namespace std;

int main() {

  // Target Vector
  vector<int> vec1 {10, 20, 30}; 

  // Source Vector
  vector<int> vec2 {40, 50};

  // Insert vec2 into vec1 at pos 1  
  vec1.insert(vec1.begin() + 1, vec2.begin(), vec2.end());

  // Print result 
  for(int x : vec1) {
    cout << x << " "; 
  }

  return 0;
}

This inserts 40 and 50 at position 1 in vec1 and prints:

10 40 50 20 30

The algorithm is:

  • Specify insert position in target vector
  • Get iterators from source vector
  • Insert using these iterators

This copies all elements from one vector into another easily.

7. Adding Elements using Array Range-based for Loop

Modern C++ provides a simpler way of iterating arrays using range-based for loops:

for (element : array) {
   // body
}

This automatically loops through array elements without needing index variables.

We can combine it with auto to simplify code that adds elements:

For example:

#include <iostream>
#include <vector>
using namespace std;

int main() {

  vector<int> vec {10, 20, 30, 40};

  // Add elements using range-based loop
  for(auto& element : vec) {
    element += 5; 
  }

  // Print 
  for(auto element : vec) {
    cout << element << " "; 
  }

  return 0;
}

This automatically loops through the vector and adds 5 to each element.

Much simpler than manually handling indexes!

So modern C++ provides easier syntax to append/insert elements into arrays and vectors.

8. Using List Containers

Vectors allow fast access but inserting elements in middle is slow since existing elements need to be shifted.

Lists are sequence containers that allow constant time insertion/deletion of elements.

To add elements we can use:

#include <iostream>
#include <list>
using namespace std;

int main() {

  // Create empty list
  list<int> lst;

  // Add elements  
  lst.push_back(10);
  lst.push_back(20);

  // Insert 60 before 20
  auto it = lst.begin();
  it++;
  lst.insert(it, 60); 

  // Print List 
  for(auto element : lst) {
    cout << element << " ";
  }

  return 0; 
}

This dynamically adds and inserts 60 before 20 by iterating using auto keyword.

Lists have some advantages over simple arrays and vectors:

  • Fast insertion/removal in any position
  • Dynamically allocate storage
  • No need to define size beforehand

The main drawback is that lists don‘t provide direct element access via indexes.

9. Resizing a Vector

Vectors provide a flexibility to resize themselves dynamically to accommodate new elements.

We can use the resize() method to increase the capacity as per need:

vector_name.resize(new_size)

For example:

#include <iostream>
#include <vector>
using namespace std;

int main() {

  vector<int> vec {10, 20, 30, 40};

  // Add elements 
  vec.push_back(50);
  vec.push_back(60);

  // Increase capacity 
  vec.resize(8);  

  // Insert more elements
  vec.push_back(70);
  vec.push_back(80);

  // Print 
  for(int x : vec) {
    cout << x << " ";
  }

  return 0;
}

Initially, vector capacity grows dynamically as elements are added using push_back().

Later, we explicitly resize it to contain more elements easily.

So resize() is useful when you know the total elements to add beforehand.

10. Conclusion

This guide covered different methods to add elements to arrays and vectors in C++ with sample code examples:

  • Create new bigger array
  • Use vector container
  • Create array dynamically using new
  • Insert element in middle
  • Vector insert() methods
  • Range-based for loops
  • List containers
  • Vector resize()

Vectors provide easiest dynamic insertion while lists enable faster inserts/deletes.

Modern C++ offers simpler syntax using range-for, auto etc. to append new elements.

By mastering these array addition techniques, you can write high performance C++ code that handles dynamic data efficiently.

Similar Posts