9.23 — An introduction to std::vector

In the previous lesson, we introduced std::array, which provides the functionality of C++’s built-in fixed arrays in a safer and more usable form.

Analogously, the C++ standard library provides functionality that makes working with dynamic arrays safer and easier. This functionality is named std::vector.

Unlike std::array, which closely follows the basic functionality of fixed arrays, std::vector comes with some additional tricks up its sleeves. These help make std::vector one of the most useful and versatile tools to have in your C++ toolkit.

An introduction to std::vector

Introduced in C++03, std::vector provides dynamic array functionality that handles its own memory management. This means you can create arrays that have their length set at run-time, without having to explicitly allocate and deallocate memory using new and delete. std::vector lives in the <vector> header.

Declaring a std::vector is simple:

Note that in both the uninitialized and initialized case, you do not need to include the array length at compile time. This is because std::vector will dynamically allocate memory for its contents as requested.

Just like std::array, accessing array elements can be done via the [] operator (which does no bounds checking) or the at() function (which does bounds checking):

In either case, if you request an element that is off the end of the array, the vector will not automatically resize.

As of C++11, you can also assign values to a std::vector using an initializer-list:

In this case, the vector will self-resize to match the number of elements provided.

Self-cleanup prevents memory leaks

When a vector variable goes out of scope, it automatically deallocates the memory it controls (if necessary). This is not only handy (as you don’t have to do it yourself), it also helps prevent memory leaks. Consider the following snippet:

If earlyExit is set to true, array will never be deallocated, and the memory will be leaked.

However, if array is a std::vector, this won’t happen, because the memory will be deallocated as soon as array goes out of scope (regardless of whether the function exits early or not). This makes std::vector much safer to use than doing your own memory allocation.

Vectors remember their length

Unlike built-in dynamic arrays, which don’t know the length of the array they are pointing to, std::vector keeps track of its length. We can ask for the vector’s length via the size() function:

The above example prints:

The length is: 5

Just like with std::array, size() returns a value of nested type size_type (full type in the above example would be std::vector<int>::size_type), which is an unsigned integer.

Resizing a vector

Resizing a built-in dynamically allocated array is complicated. Resizing a std::vector is as simple as calling the resize() function:

This prints:

The length is: 5
0 1 2 0 0

There are two things to note here. First, when we resized the vector, the existing element values were preserved! Second, new elements are initialized to the default value for the type (which is 0 for integers).

Vectors may be resized to be smaller:

This prints:

The length is: 3
0 1 2

Resizing a vector is computationally expensive, so you should strive to minimize the number of times you do so. If you need a vector with a specific number of elements but don’t know the values of the elements at the point of declaration, you can create a vector with default elements like so:

This prints:

0 0 0 0 0

We’ll talk about why direct and brace-initialization are treated differently in lesson 16.7 -- std::initializer_list. A rule of thumb is, if the type is some kind of list and you don’t want to initialize it with a list, use direct initialization.

Compacting bools

std::vector has another cool trick up its sleeves. There is a special implementation for std::vector of type bool that will compact 8 booleans into a byte! This happens behind the scenes, and doesn’t change how you use the std::vector.

This prints:

The length is: 5
1 0 0 1 1

More to come

Note that this is an introduction article intended to introduce the basics of std::vector. In lesson 10.11 -- std::vector capacity and stack behavior, we’ll cover some additional capabilities of std::vector, including the difference between a vector’s length and capacity, and take a deeper look into how std::vector handles memory allocation.


Because variables of type std::vector handle their own memory management (which helps prevent memory leaks), remember their length, and can be easily resized, we recommend using std::vector in most cases where dynamic arrays are needed.

9.24 -- Introduction to iterators
9.22 -- An introduction to std::array

234 comments to 9.23 — An introduction to std::vector

  • sai

    Hi Alex,

    Please give me a good link to read data structures.

  • Anastasia

    how does std::vector resize itself?

    I'm playing with assignment 3 from chapter 9 quiz (just the idea of it, I haven't finished that chapter yet, just need some practice), so I want my custom array to implement some functionality similar to that of std::vector. operator<< is supposed to push new elements to the back of the array and it's meant to resize accordingly. The only solution I've come up with is to allocate a new area of memory, copy all the elements to it and free the old one. Well, it works, but seems awfully inefficient way to do it, so I wonder if there's a way to request some more bytes from the system and just add them (preferably the whole will still be considered as a contiguous area of memory)?

    The way I do it now :/

    I guess I could request a big chunk initially and then to do the procedure above only if I run out of it, but it seems like wasting resources...

    edit: and looking at this code now I realize that some checks whether the memory was actually allocated to `new_array` and whether `m_array` is a valid array (not a nullptr) before dereferencing it wouldn't it hurt too :/

    • > a way to request some more bytes from the system and just add them
      Nope. You might be able to request memory after the end of your current array and still safely access it. But you'd have to keep track of all allocations for when you free the memory. This isn't reliable enough to be worthwhile.

      > The way I do it now
      - Use array syntax for arrays.
      - Initialize your variables with brace initializers.

      > I guess I could request a big chunk initially and then to do the procedure above only if I run out of it
      That's pretty much how implementations do it. If you push one element, it's likely that you'll push more afterwards. When your array is full, add a bit of extra space just in case there's more to come. You can delegate the task to the user of your class by adding a "reserve" function (Also part of `std::vector`). It's what `getNewAddress` does, but with a parameter to set the new size. Before the user pushes a lot of elements, eg. in a loop, they call `reserve` to prevent reallocations while pushing.

      • Anastasia

        > You might be able to request memory after the end of your current array and still safely access it.
        Having a separate pointer for it? Or I can do it with just one pointer somehow?

        > Use array syntax for arrays.
        But why it's bad to use pointer syntax here? It's clearer this way that I'm dealing with pointers, at least to me.

        > Initialize your variables with brace initializers.
        Where? I only do assignments in that snippet...

        > That's pretty much how implementations do it.
        Ok, I see. Will implement it this way then.

        • > Having a separate pointer for it? Or I can do it with just one pointer somehow?
          "But you'd have to keep track of all allocations for when you free the memory."
          You need another list with all the pointers of your allocations to delete them later.

          > It's clearer this way that I'm dealing with pointers
          But you're not. You're dealing with arrays.

          > Where? [brace initialization]
          Line 14

          • Anastasia

            > You need another list with all the pointers of your allocations to delete them later.
            I see, I'll try it too, seems like an interesting idea.

            > You're dealing with arrays.
            Which are pointers.

            > Line 14
            Fixed. I wasn't aware that I can use brace initialization is that case.

            Thank you!

            • > Which are pointers
              So you'd never use array syntax, because arrays can decay to pointers. `IntArray` also doesn't need `operator[]`, because it's a `class`.
              It's more important where a pointer points to than that it's a pointer.
              Using array syntax for arrays expresses what you're doing. Say someone who barely knows C++ looks at your code. It's way easier to understand what you're doing if you use array syntax.
              You're making the optimizer's job harder by using alternative approaches to reach the same goal.

              > I wasn't aware that I can use brace initialization is that case
              If you use `=` during initialization, you're doing it wrong. You can only not use brace initialization when the type you're initializing has a list constructor (And you don't want to call the list constructor). List constructors are covered later.

              • Anastasia

                > So you'd never use array syntax, because arrays can decay to pointers.
                I don't understand why those things can't be combined, if c-arrays are arrays AND pointers at the same time?

                > `IntArray` also doesn't need `operator[]`, because it's a `class`.
                This is not a valid point, sorry. If I overload the `operator[]` for the class that has array functionality, I do so for the user of the class. How I do it internally doesn't (at least in my understanding it shouldn't) matter. My little pointer arithmetics doesn't hurt the eventual user in any way.

                > You're making the optimizer's job harder by using alternative approaches to reach the same goal.
                I have no idea how optimizers work, but I'd guess it knows better than me that we are dealing with pointers here, why would it care where they are pointing?

                • It's about expression of your intentions to both the reader and the compiler.
                  The compiler doesn't need to know that the pointer is pointing into an array. It will produce the same instructions for a pointer and for an array.
                  The optimizer needs to know what you're doing and what your data looks like to be able to optimize it. I don't think there's anything here to be optimized, this is a general point. You'll be able to compile your code and it will do the same either way, but if the optimizer misses something because you weren't clear about your intentions, that's unfortunate.

                  A very simple example, not about an optimizer, but analyzer (What I said applies to everything that tries to understand your code):

                  To you it's obvious that line 5 and 6 are the same thing. Not so much to clang with -Warray-bounds. It warns you about line 5, but line 6 is silent.
                  The compiler didn't care about where `arr` points, but the analyzer needs to know that you're accessing an array.
                  I know you don't have statically sized arrays and this example doesn't apply to your code. I'm trying to show you the general idea of why your code should be expressive.

                  • Anastasia

                    Hm, it's surprising to me that the analyzer can't see that the lines 5 and 6 are identical if the `arr` was initialized as a fixed array just above...

                    Thank you for taking the time to clarify your point, at least now I see that it's not just you not liking the syntax :D And `-Warray-bounds` seems to be a useful flag (even if it's a bit dumb (sorry, clang)), I'm going to add it to my flags too.

                    • > Thank you for taking the time to clarify your point
                      You're welcome, I'm glad I managed to convince you :)

                      > I'm going to add it my flags too
                      It's on by default.

  • Vignesh

    Hi team,

    This is very very useful site for c++ learners. Can you please do a similar kind of page for c and data structures.


    • potterman28wxcv

      (disclaimer, i'm not from the team, just another person following these tutorials)

      Hi !

      C++ and C programming are very different. I'm coming from the C side.. The way of thinking is not the same - on C++ you will privilege strong typing, maintenance, readability.. With the C language you privilege the language simplicity (the C language is very easy to understand due to having a minimal amount of features), so that compilers have an easier time generating machine code (generating machine code for C++ is very very challenging), this comes at the cost of weaker typing, harder to maintain (due to less builtin features - you have to re-implement all the basic stuff).

      What C++ provides as namespaces, function overloading, classes.. In C you have to use smart naming so that your identifiers do not conflict. For instance in C++ I could create a class representing a linked list (a famous data structure), with methods to e.g. append. In C, I would create a struct represetning a linked list, and the methods would be named like "ll_append" so that there is no name conflict with other data structures that would have an "append" method.

      If you want to code C after this tutorial, I would say, just go on: you will discover by yourself all the features that C++ provide and that C doesn't. There are some specific features of C that C++ doesn't have, but it's very minor.

  • nomad

    Hi, Alex!
    "Just like with std::array, size() returns a value of nested type size_type (full type in the above example would be std::vector::size_type), which is an unsigned integer."
    Maybe you meant std::vector<int>::size_type instead of std::vector::size_type? There always should be a template parameter

    • Alex

      Yup, the <int> was being interpreted as HTML and not shown. I encoded the braces and now it's showing as intended. Thanks for pointing this out.

  • Mehul Malik

    Can u please explain the line num 11

  • NooneAtAll

    It might have been a bad idea to *name* vectors "array"

    nobody names their variable "int", because it is confusing. why naming it "array" is less so?

  • Nguyen

    Hello nascardriver,

    Note that in both the uninitialized and initialized case, you do not need to include the array length at compile time. This is because std::vector will dynamically allocate memory for its contents as requested.

    Examples in English:
    You don't need to go there (if you want to go there, it is still fine without any problem).
    You must not go there (if you go there, you will have a problem)

    I've been learning English.  When I read "you do not need to include the array length at compile time or no need to specify length at initialization", it sounds like I would not have any problem/error if I want to include the array length.

    My silly question:  Can I include the array length at initialization or compile time?  If yes, how would they look like in line 5, 6 and 7?

    • @std::vector has a constructor which allows you to set the length.

      You can't set the length _and_ elements during initialization, you have to choose one or the other.

  • Nguyen

    Hello Alex & nascardriver,

    Please help. Something is wrong with my program...

    • * Line 7, 14, 19: Initialize your variables with brace initializers. You used copy initialization.
      * Line 10: Initialize your variables with brace initializers.
      * Use auto-format.

      You're accessing elements that don't exist in line 16. Use

      If you have problems with a program, always say what you expect it to do and what it actually does.

      • Nguyen

        Hi nascardriver,

        In this lesson, all the examples used initializer list and uniform initialization to initialize arrays.  So, I wanted to see if I could use std::cin instead, just like we can do in 6.9a — Dynamically allocating arrays (Quiz).

        Sorry I did not say anything about the problem.  Compile is ok.  Error message is shown when I run....I don't know how to describe the error message.

        In short, can I use std::cin to get number/value from keyboard and store it in each element?
        I thought line 16 would allow me to do so (this line is very similar to line 41 in the solution to the quiz in 6.9a - Dynamically allocating arrays).

        Thanks, have a great day.

        • When you construct an @std::vector using the default constructor, the vector is empty.
          You can construct an @std::vector with a specific count of elements

          @vec contains 12 element, all of which are 0.
          Now you can access the elements without having to push them.

          Since the first thing you to is write to the elements (Before reading), it's unnecessary to default-initialize the elements. You can use @std::vector::reserve to allocate memory once and then use @std::vector::push_back to set the elements.

          Lesson 7.10 will elaborate on @std::vector's memory handling.

          • Nguyen

            Hi nascardriver,

            Sorry for my poor English, I don't understand your explanation at all.  But, I think you understand what I wanted to see from the output.  

            Let's make this simple. Below is the output I'd like to see.

            How many numbers would you like to enter? 3
            Enter your numbers:
            You entered: 1 2 3

            Could you please modify or fix my program?  Once you see your program, I'll figure it out.


              • Nguyen

                Thanks nascardriver.

                "Unlike a fixed array, where the array size must be fixed at compile time, dynamically allocating an array allows us to choose an array length at runtime."  

                Please let me know if below lines are the same?

                Thanks again.

  • NXPY

    Isn't it wrong to name a variable after a data type . Won't naming a variable "array" cause confusion ?

    • Hi!

      It is. The type can be part of the name, in form of a pre- or postfix, but it shouldn't be the entire name. Names should describe the value the variable is holding or what it's used for. The type alone is barely helpful for a reader.

  • Lucieon

    what's the difference between:


    You used the former here on this tutorial and the latter in the for each loop tutorial.

  • Louis Cloete

    @Alex, under the heading "Compacting bools," you wrote: "This happens behind the scenes, and is largely transparent to you as a programmer." Shouldn't it be: "This happens behind the scenes, and is largely *opaque* to you as a programmer."?

  • Mireska

    Is there a reason for not using std::vector over a build-in dynamically allocated array? Assuming that I can put vectors in vectors I don't see one myself, but I haven't tested if I can yet. Any other compelling reasons not to use this much easier, much more (time)efficient method?

    • nascardriver

      Hi Mireska!

      Unless you need to work close the the system you should use std::array or std::vector. As long as you use them correctly there's no downside to them.
      Vectors can store vectors.

  • Blaž

    Hi Alex,

    is there a difference between



    • nascardriver

      Hi Blaž!
      This depends on the type of the element. If it's a non-pointer type the order doesn't matter, however when it is a pointer the location of const changes the meaning.

  • koutarou

    I have a question regarding defining the size of the vector by user input E,G;

    how can I get that inserted into the vector so it allocates
    4 elements of space to the vector to assign values to those

    Once I know how to do that, assigning an actual value to the
    indices is not a problem through a for loop to iterate across the size of the vector storing a value in each of the element locations.

    Thank you for your time.

  • Robert

    Dear Alex, after the curly brackets of the main function in the last three example codes you set a semicolon. Is that intentionally or a typo? Thanks for your great tutorials!

  • Taksh

    Hi ALex,

    I was writing some code and tried to use a pointer to a 2 dimensionsal array, but it didn't work.
    How can I use it?

    Thanks in advance.

    • Alex

      See chapter 6.14, pointers to pointers. There's code there addressing 2d/multidimensional arrays (for 2d arrays, you need pointers to pointers).

  • justAnotherConfusedStudent

    Is there any reason #include <vector> is before #include <iostream> instead of after it, like we did with #include <string>?

    • Alex

      No. The order of includes should not matter (except if you're using visual studio precompiled headers, in which case the #include "stdafx.h" needs to be first).

      If you ever find a situation where the order of includes does matter, that means one of the headers you are including isn't properly including all of the header it needs to operate.

  • Mr C++

    You said, "Resizing dynamically allocated arrays is complicated. ".
    But, How to do so ?
    You Will Tell That Later Or Is it something else?

    • Alex

      I do cover that later, I think when we discuss container classes. You only need to know how to do it if you're creating your own containers, which you generally shouldn't do unless no other options are available.

  • Help

    can you say what is wrong with this code(it must print the maximum product of adjacent elements but it does not)
    I did not wrote the main function yet, because the problem is in this function

  • thang

    Hey Alex why when i use sizoef(array) it didn't print as expect;

    #include <iostream>
    #include <vector>

    int main()
        std::vector<int> array{ 1,2,3,4,5 };
        std::cout << array.size() << "\n" << sizeof(array) << "\n";

    this above code prints 5 and 16 ???

    • Alex

      sizeof() only counts the size of statically allocated memory. It doesn't not account for dynamically allocated memory. Your std::vector uses 16 bytes of memory (whether it is empty or not). The elements themselves are allocated in dynamically allocated memory, and thus, not counted for the size.

      This is because sizeof() is resolved at compile time, and the compiler can only keep track of statically allocated memory.

  • Deepanshu

    Hi Alex,
    If we want to dynamically allocate a collection of elements, then I want to know which way is faster? Dynamically allocating them by using the 'new' operator on the array or by using a std::vector? Please help.

  • gyuren

    My bad SENSEI,,,,,
    meant to say Visual Studio 2013 ULTIMATE v4.5 and not VISUAL BASIC 2013 ULTIMATE.
    I also tried running the std::vector implementation in the code blocks but that too fail.
    But will get a fresh copy of the code blocks and follow the procedures in lesson 0.5 and will give you the feedback.
    I am always humbled by your infinite wisdom and plenty thank you

  • gyuren

    Hello to everyone,
    and Sir Alex you are doing a magnificent job.

    I have read through all the comments and have tried all solutions suggested here to resolve c++11
    compatibility but all fail me.In addition,I have tried running the c++11 vector implementation in
    VISUAL BASIC 2013 ULTIMATE v4.5,GCC and Clang compilers all have failed.I would've tried VISUAL
    BASIC 2015 but the file size is not bandwidth friendly
    Now the question:
    Can someone please give me compiler/IDE settings or version which will allow the implementation of the c++11/14
    features.I am a windows guy and a C++ newbie by the way and thank you

    • Alex

      You need Visual C++, not Visual Basic. Visual Basic is a different language. If you look back at lessons 0.5 and 0.6, they show how to install some compilers and configure them for C++11. If bandwidth is a concern, I recommend Code::Blocks.

  • Roy

    Hi Alex,

    I have a question about std::vector and where it is stored in memory. From what I understand from the comments, if you declare a vector without the new keyword it will be stored in the stack and if the new keyword is used it will be stored in the heap, correct? For example:

    Will cause vector1 to be stored in the stack and vector2 to be stored in the heap, correct? Therefore vector1 will be (more) limited in size because of the size constaints on the stack, but have the advantage of self-cleanup, while vector2 will not have the same size limitations, but will have the disadvantage that it does not self-cleanup.

    I also feel that it might be a good idea to add this info to the tutorial, since it is important to be aware of when working with large vectors.

    • Alex

      Kind of. The vector1 object will be allocated on the stack, and the vector2 object will be allocated on the heap. However, std::vector does its own dynamic memory management, so the memory used by the vector will ALWAYS be allocated on the heap, regardless of whether the vector object itself is allocated.

      So the reality is this:
      The vector1 object is on the stack, but the memory it uses is on the heap
      The vector2 pointer is on the stack, the std::vector it points to is on the heap, and the memory it uses is on the heap

      • Jukka


        I think this needs a bit of correction:
        The vector1 object is on the stack, but the memory it uses is on the heap
        The vector2 object is on the *heap, and* the memory it uses is on the heap

        To allocate memory on the stack, an array needs to be used instead. One could use std::array to get stack-allocated memory in C++11 (but this requires knowing the size in advance, just like with C arrays).

      • Sai

        Hi Alex, can you please elaborate on this. By saying "The vector1 object is on the stack, but the memory it uses is on the heap" do you mean that memory for object Vector1 is allocated on stack, but the elements of the Vector are allocated on Heap?

        • nascardriver

          Yes, that's what Alex was trying to say.

          • Sai


            can you please share one correct link that describes the differences between arrays and vectors?

            I have read few links on the web and they are confusing to me.


            • nascardriver

              An array is a list of elements with random access, ie. you can use the `[]` operator to get any element you like. Built-in arrays have a fixed size and provide no functionality other than the `[]` operator and their size.
              A `std::vector` is a wrapper around a dynamically allocated built-in array. On top of the features of a built-in array, it provides dynamic resizing and a lot of convenient functions (`push_back`, `size`, etc.).
              A `std::array` is closer to a built-in array. It's size has to be known at compile-time and it can't resize. There's no distinction between length and capacity, because all elements are accessible at any time. Like `std::vector`, `std::array` has functions that make it easier to use than a built-in array.
              Use `std::array` if your list always has the same length and you know the length at compile-time. Use `std::vector` (Or another container/adapter) for dynamic array. Use built-in arrays if you need to manage the memory yourself, which should be rare.

    • Matej

      How many heap allocations would be necessary for vector2? Will it allocate a memory for itself and its internal buffer in one allocation or two separate allocations will be executed?

      • nascardriver

        It's 2 separate allocations. One from the `new`, which allocates the `std::vector`, and then another one inside of `std::vector` to allocate the array.

  • Dave

    Hi, Alex.

    Nice tutorials!

    I use std::vector to create dynamic one- and two-dimensional arrays.
    One aspect I am presently curious about is initializing all their values to 0.

    If I prompt a user to input an integer value for the size of the arrays, then dynamically create those arrays, will those arrays be zero initialized to default? For example, if I am using arrays of type double, will the entries of those arrays be 0.0 by default (without me looping through them and assigning all their entries 0.0)?

    • Alex

      std::vector won't zero-initialize the members in its default form, but it has an alternate form that will:

      std::vector *v1 = new std::vector(5); // no zero-initialization
      *v2 = new std::vector(5, 6.7); // initialize all members to 6.7

      You can use 0.0 instead of 6.7 if you want to initialize to 0.0.

      • Dave

        Thanks for the info, Alex.

        Is there also a way to initialize in a resize operation?

        So, instead of resizing the array at declaration, can it be resized AND initialized later?

        For example,

        I tried to compile this code but the compiler didn't like it.

        • Alex

          I'm not aware of any way to do a std::vector resize and assignment in one step. Generally you'll do the resize first, then assign values to individual elements, or the entire vector.

  • John J

    So, originally I just wanted to see what would happen with the first example in C++11 at the top of the page (right before "self clean-up prevents memory leaks") and I recognized i needed to print out the arrays to see what they would do.  In order to do that I needed a length variable for my for loop.  I kept getting 12/4 and only 3 digits (0,1,2), so then...I just took the second part out completely, and now I'm STILL getting 12/4 and 3 digits printing?!?  Shouldn't I be getting 20/4 and 5 digits (0,1,2,3,4,5)?  What's going on, and what did I miss here?

    • Alex

      You're getting the wrong result for a few reasons.

      First, think of a std::vector like a struct, like this:

      If you take the sizeof() this struct, it will only give you the sizeof the int plus the sizeof the std::string pointer. It will not give you the size of the dynamically allocated array, which is what you actually want!

      You really only should be using sizeof() for fundamental data types, which std::vector is not. If you want to know how many elements are in your std::vector, you can actually just ask it by using the .size() member function, like this:

      Remember, in this context, size() actually means length, not number of bytes.

  • R2New

    Mate, this is brilliant! I am really happy I came across your lessons. cplusplus(dot)com for example is terrible to read and understand. I gonna donate as soon as I land a job.

  • Juan

    I am feeling a little bit stupid, but I am not able to declare and initialize a vector. This is my code:

    using namespace std;

    int main()
    array2 = { 9, 7, 5, 3, 1 };
    return 0;

    But when I try to compile it I get the error:

    main.cpp: In function ‘int main()’:
    main.cpp:14:45: error: in C++98 ‘array2’ must be initialized by constructor, not by ‘{...}’
    std::vector array2 = { 9, 7, 5, 3, 1 };
    main.cpp:14:45: error: could not convert ‘{9, 7, 5, 3, 1}’ from ‘’ to ‘std::vector’
    make: *** [main.o] Error 1

    I guess one option would be to switch to C++11, but isn't there a way in which I can create a vector without adding the elements one by one in C++98?


    • Alex

      You can do this, but it's hacky:

    • Floyd

      The examples using uniform initialization don't compile on my Linux machine even on the console. Using Linux Mint with g++ version 5.4.0. Everything else in the <vector> library seems to be fine. Very interesting learning about this class.

      • Hi Floyd!

        Make sure you're compiling with the newest standard available in g++ 5.4.0

        Uniform initialization was added in c++11.

        • Floyd

          Thanks. But I mentioned in my message that by using apt-get I had installed 5.4.0. Also set up a one version older (but still supported) version of Mint with 5.4.0 but got the same results. This is what Sherlock would call a two pipe problem, but I'm no Sherlock. I did a sanity check for mistakes using an online compiler and my Windows bloatware10 (with Netbeans) and it compiled there. If I ever figure it out, I'll post it

  • Ninja

    I get an error that says debug assertion failed! vector subscript out of range. I thought you can set the length to whatever you want…

    • Alex

      With a std::vector, using operator[] or the at() function will not change the length of the vector. To change the length of a vector, you need to call resize() (or another function that explicitly changes the vector's length). I thought I'd mentioned this, but apparently not. I'll add it to the lesson.

      • Ninja

        I usually write all the code on visual studio as I read the lesson so I got confused when I got an error from the very start. I now understand after I got to the end of the lesson.

  • chump

    Hi Alex, I was messing around and found that this seems to be legal.


    I was under the impression that std::vector, by default, is dynamically allocated (heap). I also noticed that the above line is not deallocated automatically when going out of scope.

    Could you clarify whats going on here?

    Btw, great explanations on the tutorials. Thanks a lot for this.

    • Alex

      You're dynamically allocating a std::vector on the heap. Because you're the one doing the dynamic allocation, C++ expects you to do the cleanup (deletion).

      If you'd defined this as a local variable:

      it would be cleaned up automatically when v goes out of scope.

      Now, std::vector does do its own internal memory allocation to resize itself to hold the elements. This happens on the heap as well. But that's irrelevant in this example.

      • chump

        Interesting. So

        is functionally identical to

        with the only difference here being that the std::vector in the 2nd code snippet cleans itself up when going out of scope?
        The 2nd code snippet one is also in the heap (like the one in the 1st code snippet), right?

        • chump

          Seems like I misunderstood what v is in

          &v is located on the stack and effectively "points" to the dynamic memory (I’m assuming this because &v and &(v[0]) are completely different memory addresses) that holds the vector values (it seems to do the dereferencing implicitly).

          So by declaring

          I’m moving this "v" equivalent value to the heap.

          the pointer above from the second snippet is stored in the stack and points to this "v" equivalent value. I came to this conclusion after printing out value for:

          &pointer             //009FF928
          &(*pointer)         //00C58BC0
          &((*pointer)[0])   //00C5F100

          Or am I completely off again?

        • Alex

          In the first example, vector v is dynamically allocated on the heap, so you have to clean it up.
          In the second example, vector v is allocated on the stack, so it will clean itself up when it goes out of scope. So they are not the same.
          In both cases, when the vector dynamically allocates memory internally to hold your integers, that happens on the heap. The vector will clean this up when it is destroyed so you don't have to worry about it.

          I talk more about the heap and the stack in the next chapter.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]