Vector and array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Vector and array

what is difference between vector and array? explain with example plzzz

18th Jun 2017, 8:16 PM
Sonu Kumar Singh
Sonu Kumar Singh - avatar
5 Answers
+ 3
include <vector> lib, andt then create std::vector object like: std::vector<int> intTab; Vector is a class template, which means in <> you put the class which vector will contain, like in above example our vector will contain "int" objects
18th Jun 2017, 9:22 PM
Jakub Stasiak
Jakub Stasiak - avatar
19th Jun 2017, 4:06 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
array is static, once you set number of elements, you cannot change it. Vector is dynamic array, which means you can add and remove elemens as you want ^^
18th Jun 2017, 9:08 PM
Jakub Stasiak
Jakub Stasiak - avatar
+ 1
An array, like int arr[5]; is static, once declared it cannot change its size. It's easy to use and you don't have to manage any memory yourself. If you have game where entity data is continuously added and removed there is no way for you to pull this off with a static array. To pull this off you have to use a dynamic array, a dynamic array can change its size but the big drawback is that they are really hard to manage correctly. This is where a vector comes in, which is a wrapper of a dynamic array so that you don't have to deal with all the difficulties. A vector also has many functions available to aid you in your struggles, like: size of the array, copying, easy iteration, easy to add/remove data, out-of-bounds checking, easy to use together with the rest of the stl library and much more. Here's a quick example where the user can enter a number and 0 to n - 1 is added in reverse order :) (I'm too lazy to link with the code playground, but you can earn some experience by typing it yourself :P) #include <iostream> #include <vector> int main() { std::vector<int> v; int i; std::cin >> i; while(i--) v.push_back(i); for(const auto &it: v) std::cout << it << " "; return 0; }
18th Jun 2017, 9:34 PM
Dennis
Dennis - avatar
0
how can I declare vector?
18th Jun 2017, 9:09 PM
Sonu Kumar Singh
Sonu Kumar Singh - avatar