0

Vectors

I looked up the max capacity of a vector in c++, people were saying it can hold as many values as you want, if this is the case. Whats the point of arrays? why vector<int> test = {...}; why not int array[10] = {...};

14th Aug 2018, 4:29 AM
Harry
Harry - avatar
10 odpowiedzi
+ 1
Hazer C++ Begginer vector is resizable easily and can be used when you are not sure about number of members to be added into container... array is well for fixed size of allocation
14th Aug 2018, 5:43 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 4
Arrays are allocated on the stack or in a data section of the program, while vectors are allocated on the heap. Performance wise, it’s very cheap to allocate things on the stack or to use a data section, while it’s not so cheap to allocate things on the heap. That is one of the main reasons to prefer arrays over vector where you can. It should also be noted that std::array<int, 10> is a better alternative to raw arrays.
14th Aug 2018, 7:38 AM
aklex
aklex - avatar
+ 1
Hazer C++ Begginer I am sorry but could not get your point... do your question ask necessity for vector?
14th Aug 2018, 5:37 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Thanks!
14th Aug 2018, 5:45 AM
Harry
Harry - avatar
0
yeah
14th Aug 2018, 5:41 AM
Harry
Harry - avatar
0
because if you can use an array then why use vector
14th Aug 2018, 5:41 AM
Harry
Harry - avatar
0
so if i was to use a vector, what would i do to add variables to it after declaration? also, does the vector have a size limit?
14th Aug 2018, 5:48 AM
Harry
Harry - avatar
0
vector<int> vecInput;//declaration vecInput.push_back(2);//add elements
14th Aug 2018, 5:49 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Hazer C++ Begginer , please go through this once... feel free to ask any questions if you have : https://www.sololearn.com/learn/261/?ref=app
14th Aug 2018, 5:51 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
yes
14th Aug 2018, 5:51 AM
Ketan Lalcheta
Ketan Lalcheta - avatar