Naphstor
Naphstor

Reputation: 2496

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

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?

Upvotes: 103

Views: 326371

Answers (2)

Mikhail
Mikhail

Reputation: 8028

So sometimes you'd want to do this to preallocate a static buffer, and for some reason this question is the first Google result for that task... So

static std::vector<int> buffer = [](){ std::vector<int> buffer; buffer.reserve(1000); return buffer; }();

So in this case the items in the vector will be in an unitialized state but you won't pay the direct memory allocation cost of growing the vector until you hit 1000 elements

Upvotes: 1

Chad
Chad

Reputation: 19032

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;

Upvotes: 128

Related Questions