C++11, how does std::vector take a static array initializer?

Started by
7 comments, last by SmkViper 8 years, 7 months ago

With C++11 you can initialize a vector as if it were a static array, eg.:


std::vector<int> numbers = { 0, 1, 2, 3 };

I have a class that I want to be able to declare and initialize with a static array like that. I've been reading through the <vector> header file but I'm not even sure where they're doing it, much less how. Anyone know how to do this?

Advertisement

I'm fairly certain that the complier is doing this at compile time and that it has nothing to do with how vectors are implemented in code. Sorry. Brain fart..

You'll want to look at std::initializer_list.


#include <initializer_list>
#include <iostream>

struct S {
  S (std::initializer_list<int> items) {
    for (const auto & item : items) {
      std::cout << item << "\n";
    }
  }
};


int main () {
  S s = { 1, 2, 10, 20 };
}

Awesome, thanks!

Thank you, Josh! I completely forgot about initializer lists. :o

Yep, initializer list -- not a static array at all.

throw table_exception("(? ???)? ? ???");

Initializer lists are very buggy in VisualC++ 2013, so that's what I've done several times:


#include <vector>
#include <iostream>

struct S {
    S(const std::vector<int>& items) {
        for (const auto & item : items) {
            std::cout << item << "\n";
        }
    }
};

int main () {
    S s({ 1, 2, 10, 20 });
}


Initializer lists are very buggy in VisualC++ 2013, so that's what I've done several times:

Do you have the most recent service pack for VS2013? I had some issues with initalizer list with VS2013 in its original state, but with the SP they disappeared.

You should also consider upgrading to 2015, as the CE version is free. It greatly improves C++11/14 compliance over previous versions.

This topic is closed to new replies.

Advertisement