Integer Insertion - Every Other

Integer Insertion - Every Other

Make a program with an int array of size 8. All the elements should have the value 0. Print the value of the array on one line.

Use std::vector::insert to add an element of the value 1 in between each element. Print the new value of the array on one line.

Expected output

0 0 0 0 0 0 0 0
0 1 0 1 0 1 0 1 0 1 0 1 0 1 0

Answer

#include <iostream>
#include <vector>

int main() {
    std::vector<int> arr(8, 0);

    // Print the initial array
    for (int i = 0; i < arr.size(); ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << "\n";

    // Insert '1' between each element
    int n = arr.size() * 2 - 2;
    for (int i = 1; i < n; i += 2) {
        arr.insert(arr.begin() + i, 1);
    }

    // Print the modified array
    for (int i = 0; i < arr.size(); ++i) {
        std::cout << arr[i] << " ";
    }

    return 0;
}

std::vector<int> arr(8, 0) is using a custom constructor. This sets up a std::vector<int> object with 8 elements of value 0. It's equivalent to std::vector<int> arr = {0,0,0,0,0,0,0,0}.

int n is needed to store the original size of the array. If we use i < arr.size()*2 - 2 as the condition, we create an infinite loop. As we add elements arr.size() also increases. Eventually end up with an insert statement that tries to add an element beyond the end of the array, at which point the program crashes.

Questions