vector::insert in C++ (With Examples)

Hello! Today, we’ll be diving into a useful function in C++ related to vectors – vector::insert. We’ll start with an overview, delve into its proper usage, showcase examples, and round off with a simple custom implementation to understand this function better.

What is vector::insert?

In C++, vectors are a part of the Standard Template Library (STL) and act as dynamic arrays. You can add elements, remove them, and even resize them as per your requirements. One of the crucial operations for vectors is inserting elements, and that’s where vector::insert comes into play.

The vector::insert function allows you to add an element or a range of elements at any specific position in the vector, pushing the existing elements back.

Here’s a simple example:

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

int main() {
    vector<int> vec = {10, 20, 30};
    vec.insert(vec.begin() + 1, 15);  // Inserts 15 between 10 and 20

    for(int num : vec) {
        cout << num << " ";
    }

    return 0;
}

When you run the above code, you’ll get:

10 15 20 30

The vector::insert function has multiple overloads. Let’s dive deeper into them.

Overloads of vector::insert

1. Insert Single Element

Syntax:

iterator insert (iterator position, const value_type& val);

Here, you can insert a single value val before the position pointed by the iterator.

2. Insert Elements Repeatedly

Syntax:

iterator insert (iterator position, size_type n, const value_type& val);

Using this, you can insert the val n number of times at the specified position.

Example:

vector<int> vec = {10, 20, 30};
vec.insert(vec.begin() + 1, 3, 15);  // Inserts three 15s between 10 and 20

Vector contents:

10 15 15 15 20 30

3. Insert Range

Syntax:

iterator insert (iterator position, InputIterator first, InputIterator last);

This overload allows you to insert a range of elements from another container into the vector at the specified position.

4. Insert Using Initializer List

Syntax:

iterator insert (iterator position, initializer_list<value_type> il);

With this overload, you can directly use an initializer list to insert multiple elements at once.

vector<int> vec = {10, 20, 30};
vec.insert(vec.begin() + 2, {40, 50, 60});  // Inserts 40, 50, 60 before 30

Vector contents:

10 20 40 50 60 30

How it words under the hood

When you use vector::insert, it might seem straightforward, but several things happen behind the scenes. Let’s take a closer look:

  1. Space Check: First, the function checks if there is enough space in the vector to accommodate the new elements. If not, a reallocation happens, which might invalidate all the iterators pointing to the vector.

  2. Element Shift: All elements after the insertion point are shifted back to make space for new elements.

  3. Element Insertion: New elements are inserted in the created space.

It’s crucial to know that using vector::insert might cause a performance hit, especially if you insert at a position other than the end. It’s because all subsequent elements need to be moved. So, use it cautiously!

Custom Implementation of vector::insert

To further grasp the concept, let’s craft a simplified version of vector::insert:

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

template <typename T>
void customInsert(vector<T> &vec, int pos, T value) {
  // 1. Check position validity
  if (pos < 0 || pos > vec.size()) {
    return;  // Invalid position
  }

  // 2. Resize the vector
  vec.resize(vec.size() + 1);

  // 3. Shift elements
  for (int i = vec.size() - 1; i > pos; --i) {
    vec[i] = vec[i - 1];
  }

  // 4. Insert the new value
  vec[pos] = value;
}
int main() {
  vector<int> vec = {10, 20, 30};
  customInsert(vec, 2, 25);

  for (int num : vec) {
    cout << num << " ";
  }

  return 0;
}

Output:

10 20 25 30

Note that this is a simple and illustrative version and lacks the depth and optimization of STL’s vector::insert.

Wrapping Up

The vector::insert function in C++ is a powerful tool in your arsenal when dealing with vector manipulations. However, as with any tool, understanding its intricacies and performance implications is essential. Happy coding!

Exercises

  1. Basic Use of vector::insert:

    • Write a C++ program that creates a vector of strings.
    • Prompt the user for a string and a position where they’d like to insert it.
    • Use the vector::insert function to add the string at the specified position.
    • Display the modified vector to the user.
  2. Exploring Overloads:

    • Extend the previous program to offer the user multiple options: a. Insert a single string at a specified position. b. Insert a string multiple times at a specified position. c. Insert a range of strings from another vector at a specified position. d. Insert using an initializer list.
    • Prompt the user to choose one of the options and execute it accordingly. Display the resultant vector each time.
  3. Performance Implications:

    • Write a C++ program that demonstrates the performance difference between inserting an element at the beginning vs. the end of a large vector.
    • Create a vector with a size of 100,000 filled with random numbers.
    • Measure the time taken to insert a new number at the beginning and at the end of the vector.
    • Display the time taken for each operation to the user. Reflect on why there’s a difference in time.

Discussion

© 2023, codelessons.dev