Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a vector of user defined size but with no predefined values? [closed]

Tags:

c++

vector

In C++ one can create an array of predefined size, such as 20, with int myarray[20]. However, the online documentation on vectors doesn't show an alike way of initialising vectors: Instead, a vector should be initialised with, for example, std::vector<int> myvector (4, 100);. This gives a vector of size 4 with all elements being the value 100.

How can a vector be initialised with only a predefined size and no predefined value, like with arrays?

like image 362
Naphstor Avatar asked May 11 '12 22:05

Naphstor


People also ask

How do you set the size of a vector in C++?

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector. If val is specified then new elements are initialed with val.


1 Answers

With the constructor:

// create a vector with 20 integer elements std::vector<int> arr(20);  for(int x = 0; x < 20; ++x)    arr[x] = x; 
like image 161
Chad Avatar answered Sep 20 '22 16:09

Chad