Is it possible to allow a user to enter an array size with a keyboard?

后端 未结 5 1714
萌比男神i
萌比男神i 2021-01-13 10:21

Is it possible to allow the user to enter the size of an array with a keyboard?

I know that arrays can\'t change size. The only solution I could think of is this:

5条回答
  •  一整个雨季
    2021-01-13 11:15

    Many of the other answers are correct, but to show your possible choices. Each one will fit into different situations better.

    The first one is most similar to your code. It makes a constant size array and lets the user choose how much of it to use. This is simple, but limiting. It can waste unused space, but has it places to be used. (not likely based on user input though)

    const int SIZE=100;
    int array[SIZE];
    int userSize;
    
    cin >> userSize;
    if (userSize>SIZE){
       cerr << "Array requested too large";
    }
    // use userSize as size of array
    

    The second choice is dynamic memory allocation and using a regular C pointer to keep track of it. If you forget (or are unable) to delete it you have a memory leak.

    cin >> userSize;
    int* array = new int[userSize];
    ...
    delete [] array;
    

    The third choice is writing your own smart pointer, boost, or in C++ 0x a unique_ptr. It will keep track of the pointer for you and delete it when it goes out of scope.

    cin >> userSize;
    unique_ptr array(new int[userSize]);
    

    And finally you probably just want a vector. As you hinted to in your question, a vector is probably the way to go here. They are simple, efficient, and commonly used. Learning one stl container makes learning the others easier. You should research which container fits your current problem best. Vector is a good choice most of the time.

    #include 
    ...
    std::vector vec; 
    cin >> userSize;
    vec.resize(userSize);
    

提交回复
热议问题