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.
1 answer
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
- oneCorrected. Better?) - MajorMeow
- 2and 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
- oneAnd for what a minus? - VladD
|
std::vector, and you will be happy. On C it is necessary manually, throughrealloc. - VladDvector<int>and add the next element withpush_back. The size changes automatically. - VladD