96

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?

Simon Klaver
  • 480
  • 5
  • 24
Naphstor
  • 2,356
  • 7
  • 35
  • 53
  • Read the docs? http://www.cplusplus.com/reference/stl/vector/vector/ http://www.cplusplus.com/reference/stl/vector/resize/ – Brian Roach May 11 '12 at 22:16
  • @JesseGood - I linked to both in edit, fat fingered it the first time ;) – Brian Roach May 11 '12 at 22:19
  • 3
    @BrianRoach: also you might want to read [What's wrong with cplusplus.com?](http://programmers.stackexchange.com/questions/88241/whats-wrong-with-cplusplus-com). – Jesse Good May 11 '12 at 22:21
  • There is no way. There is a highway. – mip May 11 '12 at 22:37
  • 1
    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. – Naphstor May 16 '12 at 20:55
  • 1
    the documentation is very hard to understand sometimes. http://www.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 arr(20) will work. but i also couldnt find this at first and only saw the constructor that takes 2 params (size, fillvalue) – mobooya Jul 14 '15 at 17:01
  • 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. – kriss Nov 30 '18 at 10:34
  • @JesseGood The question you are referring to is removed from the site. – user4035 Jun 30 '21 at 19:27
  • @user4035: [Here is an updated link](https://stackoverflow.com/questions/6520052/whats-wrong-with-cplusplus-com) – Jesse Good Jul 02 '21 at 04:39

2 Answers2

120

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;
Chad
  • 18,706
  • 4
  • 46
  • 63
  • 1
    Sorry, does not work for me, OS X Mavericks LLVM, default for xcode 4.2+. What compiler are you using? – patrik Feb 04 '15 at 16:01
  • 1
    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. – Chad Feb 04 '15 at 17:59
  • 3
    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 arr = std::vector (20);` worked fine for me, specifically stating that I want to use the constructor for vector. – patrik Feb 05 '15 at 06:58
  • 1
    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 arr((20));` – Chad Oct 17 '15 at 17:28
  • 2
    @Chad 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. – Sayan Bhattacharjee Mar 11 '16 at 08:59
  • 2
    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. – Chad Mar 11 '16 at 15:36
  • 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? – roschach Jun 06 '19 at 13:16
  • show your code @francesco – Chad Jun 07 '19 at 03:02
  • 5
    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 v_name = std::vector(size)``` Or alternatively define ```std::vector v_name``` and initialise the size in the constructors by just using ```class() : v_name(size) {}```. – Luismi98 Apr 03 '20 at 22:52
  • Instead of the loop, you can use [std::iota](https://en.cppreference.com/w/cpp/algorithm/iota). Example [here](https://wandbox.org/permlink/z6gfaF7mzhtftOfd). – Paul Rooney Apr 12 '22 at 00:55
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

Mikhail
  • 7,749
  • 11
  • 62
  • 136
  • When you say "the items in the vector will be in an unitialized state" you should clarify that [`reserve`](https://en.cppreference.com/w/cpp/container/vector/reserve) only changes the capacity of the vector, no item is added: https://godbolt.org/z/GxhqoahsG – Bob__ Jul 19 '23 at 08:23
  • Yep, so in this case the allocations for the simple int type have all been performed. – Mikhail Jul 19 '23 at 09:26