How to add element to C++ array?

后端 未结 11 2454
旧时难觅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-12 23:52

    Arrays in C++ cannot change size at runtime. For that purpose, you should use vector instead.

    vector arr;
    arr.push_back(1);
    arr.push_back(2);
    
    // arr.size() will be the number of elements in the vector at the moment.
    

    As mentioned in the comments, vector is defined in vector header and std namespace. To use it, you should:

    #include

    and also, either use std::vector in your code or add

    using std::vector; 
    

    or

    using namespace std;
    

    after the #include line.

提交回复
热议问题