How to add element to C++ array?

后端 未结 11 2471
旧时难觅i
旧时难觅i 2020-12-12 23:26

I want to add an int into an array, but the problem is that I don\'t know what the index is now.

int[] arr = new int[15];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;         


        
11条回答
  •  无人及你
    2020-12-13 00:12

    I may be missing the point of your question here, and if so I apologize. But, if you're not going to be deleting any items only adding them, why not simply assign a variable to the next empty slot? Every time you add a new value to the array, just increment the value to point to the next one.

    In C++ a better solution is to use the standard library type std::list< type >, which also allows the array to grow dynamically, e.g.:

    #include 
    
    std::list arr; 
    
    for (int i = 0; i < 10; i++) 
    {
        // add new value from 0 to 9 to next slot
        arr.push_back(i); 
    }
    
    // add arbitrary value to the next free slot
    arr.push_back(22);
    

提交回复
热议问题