简体   繁体   中英

How to safely insert an element into an array c++?

I have a simple program to add an element to an array:

void printArray(int inp[], int size)
{
    cout << "[";
    for (int i = 0; i < size - 1; i++)
    {
        cout << inp[i] << ", ";
    }
    cout << inp[size - 1] << "]" << endl;
}

int addElement(int inputArray[], int inputSize, int element, int atIndex)
{
    int cur = inputSize;
    while (cur >= 0)
    {
        if (cur == atIndex)
        {
            inputArray[cur] = element;
            return inputSize + 1;
        }
        inputArray[cur] = inputArray[cur - 1];
        cur--;
    }
    return inputSize + 1;
}


int arr1[] = {1, 5, 9, 2};
int arr2[] = {1, 5, 9, 2};

int main()
{
    int arraySize = sizeof(arr1) / sizeof(arr1[0]);

    addElement(arr1, arraySize, 7, 0);
    printArray(arr1, arraySize + 1);
    printArray(arr2, arraySize);

    return 0;
}

This outputs:

[7, 1, 5, 9, 2]
[2, 5, 9, 2]

Even though I haven't touched arr2 it is modified. I think because arr1 and arr2 are allocated contiguously in memory, and naively adding an element to arr1 overwrites arr2[0] .

How should I handle this case and add only if the next space is unused, otherwise move the entire array to another location?

You can achieve this easily by using std::vector . It has a method called insert , where you just pass a position and a number as arguments and it will handle the reallocation by itself.

For example: if you write:

vector<int> vec = { 1, 2, 3, 4, 5 };
vec.insert(vec.begin() + 2, 100);

Now elements in your vector are 1, 2, 100, 3, 4, 5.

I don't know if this will help you, but you can also add multiple elements at once:

vector<int> vec = { 1, 2, 3, 4, 5 };
vec.insert(vec.begin() + 3, { 100, 101 });

Now elements in your vector are: 1, 2, 3, 100, 101, 4, 5 .

As you can see, the first argument is the position of the first inserted element and the second one is element or list of elements that you want to insert.

You can read more about std::vector here and about std::vector::insert here

Hope this helps.

As what the comments mentioned by @StoryTeller, you can use a std::vector.

But you have to pick on which function of the container you wanna use, there are 2 types.

  1. ::insert , which inserts data on the specific location in the container. This is iterator based.

  2. ::push_back , which inserts at the back/last of the container

You can use any of them, depending on your purpose, just be sure of ::insert that you are pointing to the correct position(iterator wise).

Also, as of C++11 you can use ::emplace and ::emplace_back , which constructs and inserts data. You can find more at,

http://www.cplusplus.com/reference/vector/vector/

Hope this helps.

I have a simple program to add an element to an array:

Impossible. An array's size is fixed at compile time. In other words,

 int arr1[] = {1, 5, 9, 2}; 

is a lot like:

int arr1_1 = 1;
int arr1_2 = 5;
int arr1_3 = 9;
int arr1_4 = 2;

I think it is helpful, for learning purposes, to view an array like this, and not like a container which can shrink and grow while the program is running. Adding an element to an array at runtime would be like asking to add a variable at runtime. C++ arrays don't work like that.

You can use new[] to set an array's initial size at runtime, but even then you cannot "add" anything. In fact, don't use new[] , ever.

Go to cppreference.com, learn about std::vector and relearn everything from scratch. Start with the example code at the bottom of the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM