Search code examples
c++arraysinsertion

How to shift and insert an element in an array with a specified size


I'm a beginner in C++. For my assignment I was supposed to insert an element into an array at a specific index. I attempted to do it and I thought that the algorithm that I used is correct but my array won't shift.

This is my code:

 #include <iostream>
using namespace std;

const int CAPACITY = 10;

// Declaration function insertAtIndex
void insertAtIndex(int a[], int elements, int value, int index);

#include "Testing.hxx"

int main( )
{
    testCases();

    cout << endl;
    system("Pause");
    return 0;
}


void insertAtIndex(int a[], int elements, int value, int index);
{
    if (elements == CAPACITY)
        cerr << "Array is full. Cannot insert another element." << endl;
    else if (index > CAPACITY)
        cerr << "The array connot have more than 10 elements." << endl;

    else if (index > elements)
        cerr << "You can only insert continguous elements in the array." << endl;

    else
    {
        elements++;
        if (index == 0)
            a[0] = value;
        else
            for (int i = elements; i >= index; i--)
            {
                a[i + 1] = a[i];
            }
        //insert value at index
        a[index] = value;

    }

}

For some reason my code will insert the value at the index, but it will not shift the elements in the array. When it reaches the number of the elements in the array, it doesn't display anything. Also it won't insert it if the array is empty ex: when I'm suppose to insert 10 at index 0, it just says no elements in array.

This is my testing cases:

*Initial Array: No elements in the array. Insert 10 at idx 0... Modified array: No elements in the array.

Initial Array: 1 Insert 20 at idx 0... Modified array: 20

Initial Array: 3 Insert 30 at idx 1... Modified array: 3

Initial Array: 5 3 Insert 40 at idx 1... Modified array: 5 40

Initial Array: 5 3 1 7 Insert 60 at idx 4... Modified array: 5 3 1 7

Initial Array: 8 4 2 6 7 8 2 Insert 80 at idx 7... Modified array: 8 4 2 6 7 8 2

Initial Array: 9 8 5 6 3 2 1 4
Insert 90 at idx 8... Modified array: 9 8 5 6 3 2 1 4

This is what I'm suppose to achieve on a successful case:

Initial Array: 9 8 5 6 3 2 1 4

Insert 90 at idx 8...

Modified array: 9 8 5 6 3 2 1 4 90

This is the testing code:

#ifndef TESTING_H
#define TESTING_H

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

vector< vector<int>> v = { { },
{ 1 },
{ 3 },
{ 5, 3 },
{ 7, 4 },
{ 5, 3, 1, 7 },
{ 4, 2, 7, 4 },
{ 8, 4, 2, 6, 7, 8, 2 },
{ 9, 8, 5, 6, 3, 2, 1, 4 },
{ 1, 6, 4, 8, 9, 0, 7, 5, 2, 3 },
{ 4, 6, 2}, 
{ 0, 1, 2, 3, 4, 5, 6 ,7 ,8, 9 } };

int indices[] = { 0, 0, 1, 1, 2, 4, 5, 7, 8, 10, 20, 5 };

void printArray(const int a[], int numOfElements)
{
    if (numOfElements == 0)
        cout << "No elements in the array.";
    else
        for (int i = 0; i < numOfElements; ++i)
            cout << a[i] << " ";
}

void testing(int i)
{
    int a[CAPACITY];
    int numOfElem = static_cast<int>(v[i].size());
    for (int j = 0; j < numOfElem; ++j)
        a[j] = v[i].at(j);
    cout << "Initial Array: ";
    printArray(a, numOfElem);
    cout << endl;
    int elem = (i + 1) * 10;
    cout << "Insert " << elem << " at idx " << indices[i] << "...\nModified array: ";
    insertAtIndex(a, numOfElem, elem, indices[i]);  
    printArray(a, numOfElem);
    cout << "\n--------------------------------------------------------\n";
}
void testCases()
{
    int vectorSize = static_cast<int>(v.size());

    for (int i = 0; i < vectorSize; ++i)
    {
        testing(i);
    }
}

#endif

Solution

  • One issue with this code is that you increment elements, then use it as the initial value of the loop index i, then write to a[i+1]. However, you really want to start with index elements (the unincremented value), the last valid index in the enlarged array. This error will cause undefined behavior if you are within one element of capacity.

    Another is that you only increment the function parameter named elements, which is a temporary copy. It will not be passed back. Therefore, your array never grows. If you declare your function parameters const, the compiler will catch this bug for you.

    I would in general encourage you to declare a new const variable when you calculate a new value, rather than change the value of an existing variable. (One exception to the rule: incrementing or decrementing a loop counter.) Either you’ll need the old value again, in which case overwriting it is a bug the compiler can’t catch, or you won’t, in which case the optimizer’s dependency analysis should be able to figure out it can discard it. You’re also less likely to make mistakes like this, where you increment elements and then add 1 to it again because you forgot that you changed it.

    You did not show us your testcases() function, so I can neither compile this code nor review the missing piece. Please provide a MCVE, as that will make it possible to help you.

    This is a good opportunity to learn to run your program in a debugger, insert a breakpoint, and single-step through the loop. It’s a good place to start when you get this kind of bug.