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

2

101

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?

Beatty answered 11/5, 2012 at 22:13 Comment(9)
Read the docs? cplusplus.com/reference/stl/vector/vector cplusplus.com/reference/stl/vector/resizeTombaugh
@JesseGood - I linked to both in edit, fat fingered it the first time ;)Tombaugh
@BrianRoach: also you might want to read What's wrong with cplusplus.com?.Jurisdiction
There is no way. There is a highway.Deceased
sorry to all, it was a mistake i did. I always created vector using its default constructor, never read that there is a constructor which takes two arguments, first one as the number of elements and second with the element value. This constructor creates a vector of size defined by user and also allocates user defined values to all the positions.Beatty
the documentation is very hard to understand sometimes. cplusplus.com/reference/vector/vector/vector If you expland the c++11 tab you have to focus to find this: explicit vector (size_type n); which is basically saying that you can set the size and not the fill value, so std:vector<int> arr(20) will work. but i also couldnt find this at first and only saw the constructor that takes 2 params (size, fillvalue)Incubus
It is also not very explicit in the documentation what is done if not explicit initialization value is provided: do nothing or initialize with default value. If what you want to do is initializing the vector yourself just afterward the allocation you don't want any initialisation done before that. It's just time lost in the program.Benefaction
@JesseGood The question you are referring to is removed from the site.Health
@user4035: Here is an updated linkJurisdiction
T
124

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;
Taneshatang answered 11/5, 2012 at 22:17 Comment(10)
Sorry, does not work for me, OS X Mavericks LLVM, default for xcode 4.2+. What compiler are you using?Hammerfest
Nothing magical about the compilers I've used. This is all standard-defined behavior. If this exact code doesn't work, suspect compiler or xcode extensions that break it.Taneshatang
Ok I see, I think that LLVM uses clang for c++, so that it is weird. I thought that vector should be seen more or less like a replacement to array these days and that there should reflected in the syntax (which should be what is written by you then). Strange that my compiler does not allow that. Still, the point of this comment is to add an extension to what is already written; So, std::vector<int> arr = std::vector<int> (20); worked fine for me, specifically stating that I want to use the constructor for vector.Hammerfest
Looking back at this now, I see that it probably failed for you becaues of the "most vexing parse". Try adding some parenthesis around the 20, like this: std::vector<int> arr((20));Taneshatang
@Taneshatang It is better to use arr.at(x)=x to check for out_of_bounds errors. arr[x]=x will fail silently if some mistake occurs.Strenta
If you require range-checking yes, at() does the checking and will throw an exception for an out of bounds error, while [] does no checking.Taneshatang
I am defining a vector of unsigned short int as a member function. I want to initialize its size to 6. With your method I get Expected parameter declarator: Why is that?Geophysics
show your code @francescoTaneshatang
I would like to add that, if you are using a vector as member data of a class, the initialisation in Chad's answer will throw compiler error. You would need to do std::vector<type> v_name = std::vector<type>(size) Or alternatively define std::vector<type> v_name and initialise the size in the constructors by just using class() : v_name(size) {}.Binal
Instead of the loop, you can use std::iota. Example here.Freewheel
P
0

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

Paphian answered 19/7, 2023 at 5:9 Comment(2)
When you say "the items in the vector will be in an unitialized state" you should clarify that reserve only changes the capacity of the vector, no item is added: godbolt.org/z/GxhqoahsGStreeter
Yep, so in this case the allocations for the simple int type have all been performed.Paphian

© 2022 - 2024 — McMap. All rights reserved.