Skip to content

Instantly share code, notes, and snippets.

@char-1ee
Last active August 11, 2022 08:48
Show Gist options
  • Save char-1ee/9839a847e106f2477310fddced8e7d9a to your computer and use it in GitHub Desktop.
Save char-1ee/9839a847e106f2477310fddced8e7d9a to your computer and use it in GitHub Desktop.

Initialize vector with hardcoded elements

In C++ 11:

#include <vector>
using std::vector;
vector<int> v1 {10, 20, 30};
vector<int> v2 = {10, 20, 30};

Using Boost list_of:

#include <vector>
#include <boost/assign/list_of.hpp>
using std::vector;

vector<int> v = boost::assign::list_of(10)(20)(30);

Using Boost assign:

#include <vector>
#include <boost/assign/std/vector.hpp>
using std::vector;

vector<int> v;
v += 10, 20, 30;

Conventional STL:

#include <vector>
using std::vector;

static const int arr[] = {10, 20, 30};
vector<int> v (arr, arr + sizeof(arr) / sizeof(arr[0]));

Conventional STL with generic macro:

#include <vector>
#define ARRAY_SIZE(ar) (sizeof(ar) / sizeof(ar[0]))
#define ARRAY_END(ar) (ar + ARRAY_SIZE(ar))
using std::vector;

static const int arr[] = {10, 20, 30};
vector<int> v (arr, ARRAY_END(arr));

Conventional STL with a vector initializer marco:

#include <vector>
#define INIT_FROM_ARRAY(ar) (ar, ar + sizeof(ar) / sizeof(ar[0]))

static const int arr[] = {10, 20, 30};
vector<int> v INIT_FROM_ARRAY(arr);

Initialize array with 0

Unless that value is 0 (in which case you can omit some part of the initializer and the corresponding elements will be initialized to 0), there's no easy way.

Elements with missing values will be initialized to 0:

int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...

int myArray[10] = { 0 }; // all elements 0

In C++, an empty initialization list will also initialize every element to 0. This is not allowed with C until C23:

int myArray[10] = {}; // all elements 0 in C++ and C23

Remember that objects with static storage duration will initialize to 0 if no initializer is specified:

static int myArray[10]; // all elements 0

And that "0" doesn't necessarily mean "all-bits-zero", so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment