How to add element to C++ array?

后端 未结 11 2444
旧时难觅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<int> instead.

    vector<int> 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 <vector>

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

    using std::vector; 
    

    or

    using namespace std;
    

    after the #include <vector> line.

    0 讨论(0)
  • 2020-12-13 00:05
    int arr[] = new int[15];
    

    The variable arr holds a memory address. At the memory address, there are 15 consecutive ints in a row. They can be referenced with index 0 to 14 inclusive.

    In php i can just do this arr[]=22; this will automatically add 22 to the next empty index of array.

    There is no concept of 'next' when dealing with arrays.
    One important thing that I think you are missing is that as soon as the array is created, all elements of the array already exist. They are uninitialized, but they all do exist already. So you aren't 'filling' the elements of the array as you go, they are already filled, just with uninitialized values. There is no way to test for an uninitialized element in an array.

    It sounds like you want to use a data structure such as a queue or stack or vector.

    0 讨论(0)
  • 2020-12-13 00:08

    You don't have to use vectors. If you want to stick with plain arrays, you can do something like this:

    int arr[] = new int[15];
    unsigned int arr_length = 0;
    

    Now, if you want to add an element to the end of the array, you can do this:

    if (arr_length < 15) {
      arr[arr_length++] = <number>;
    } else {
      // Handle a full array.
    }
    

    It's not as short and graceful as the PHP equivalent, but it accomplishes what you were attempting to do. To allow you to easily change the size of the array in the future, you can use a #define.

    #define ARRAY_MAX 15
    
    int arr[] = new int[ARRAY_MAX];
    unsigned int arr_length = 0;
    
    if (arr_length < ARRAY_MAX) {
      arr[arr_length++] = <number>;
    } else {
      // Handle a full array.
    }
    

    This makes it much easier to manage the array in the future. By changing 15 to 100, the array size will be changed properly in the whole program. Note that you will have to set the array to the maximum expected size, as you can't change it once the program is compiled. For example, if you have an array of size 100, you could never insert 101 elements.

    If you will be using elements off the end of the array, you can do this:

    if (arr_length > 0) {
      int value = arr[arr_length--];
    } else {
      // Handle empty array.
    }
    

    If you want to be able to delete elements off the beginning, (ie a FIFO), the solution becomes more complicated. You need a beginning and end index as well.

    #define ARRAY_MAX 15
    
    int arr[] = new int[ARRAY_MAX];
    unsigned int arr_length = 0;
    unsigned int arr_start = 0;
    unsigned int arr_end = 0;
    
    // Insert number at end.
    if (arr_length < ARRAY_MAX) {
      arr[arr_end] = <number>;
      arr_end = (arr_end + 1) % ARRAY_MAX;
      arr_length ++;
    } else {
      // Handle a full array.
    }
    
    // Read number from beginning.
    if (arr_length > 0) {
      int value = arr[arr_start];
      arr_start = (arr_start + 1) % ARRAY_MAX;
      arr_length --;
    } else {
      // Handle an empty array.
    }
    
    // Read number from end.
    if (arr_length > 0) {
      int value = arr[arr_end];
      arr_end = (arr_end + ARRAY_MAX - 1) % ARRAY_MAX;
      arr_length --;
    } else {
      // Handle an empty array.
    }
    

    Here, we are using the modulus operator (%) to cause the indexes to wrap. For example, (99 + 1) % 100 is 0 (a wrapping increment). And (99 + 99) % 100 is 98 (a wrapping decrement). This allows you to avoid if statements and make the code more efficient.

    You can also quickly see how helpful the #define is as your code becomes more complex. Unfortunately, even with this solution, you could never insert over 100 items (or whatever maximum you set) in the array. You are also using 100 bytes of memory even if only 1 item is stored in the array.

    This is the primary reason why others have recommended vectors. A vector is managed behind the scenes and new memory is allocated as the structure expands. It is still not as efficient as an array in situations where the data size is already known, but for most purposes the performance differences will not be important. There are trade-offs to each approach and it's best to know both.

    0 讨论(0)
  • 2020-12-13 00:08

    If you are writing in C++ -- it is a way better to use data structures from standard library such as vector.

    C-style arrays are very error-prone, and should be avoided whenever possible.

    0 讨论(0)
  • 2020-12-13 00:08

    Since I got so many negative feedback I realized my solution was wrong so i changed it.

    int arr[20] = {1,2,3,4,5};
    int index = 5;
    
    void push(int n){
        arr[index] = n;
        index++;
    }
    
    push(6)
    

    New array will contain value from 1 to 6 and you can make function for deletion like this as well.

    0 讨论(0)
  • 2020-12-13 00:09

    Initialize all your array elements to null first, then look for the null to find the empty slot

    0 讨论(0)
提交回复
热议问题