How to fill an array with an unknown number of numbers in advance? The user simply enters from the keyboard 2 or 100,000 numbers and they all must be entered into the array.

  • 2
    Use std::vector , and you will be happy. On C it is necessary manually, through realloc . - VladD
  • Use a dynamic array - MajorMeow
  • @MajorMeow, and how not to specify the size? - Oleksandr Zakrevskyi
  • @VladD, is it possible in more detail about the vector? - Oleksandr Zakrevskyi
  • one
    @OleksandrZakrevskiy: Well, declare an empty vector<int> and add the next element with push_back . The size changes automatically. - VladD

1 answer 1

Actually it is better to use vector. Here is an example:

 #include <iostream> #include <vector> #include <iterator> // заголовочный файл итераторов using namespace std; int main() { vector<int> array1; // создаем пустой вектор // добавляем в конец вектора array1 элементы 4, 3, 1 array1.insert(array1.end(), 4); array1.insert(array1.end(), 3); array1.insert(array1.end(), 1); // вывод на экран элементов вектора copy( array1.begin(), // итератор начала массива array1.end(), // итератор конца массива ostream_iterator<int>(cout," ") //итератор потока вывода ); return 0; } 
  • You have specified 10 items in advance. - Oleksandr Zakrevskyi
  • one
    Corrected. Better?) - MajorMeow
  • 2
    and insert better than push_back? The latter seems to be more readable. - pavel
  • @pavel I agree, more readable. We had to write several options for adding the item. - MajorMeow
  • one
    And for what a minus? - VladD