How should I brace-initialize an std::array of std::pairs?

Neil Kirk picture Neil Kirk · Dec 27, 2014 · Viewed 11.5k times · Source
std::array<std::pair<int, int>, 2> ids = { { 0, 1 }, { 1, 2 } };

VS2013 error:

error C2440: 'initializing' : cannot convert from 'int' to 'std::pair' No constructor could take the source type, or constructor overload resolution was ambiguous`

What am I doing wrong?

Answer

user743382 picture user743382 · Dec 27, 2014

Add another pair of braces.

std::array<std::pair<int, int>, 2> ids = { { { 0, 1 }, { 1, 2 } } };

std::array<T, N> is an aggregate class containing a member of type T[N]. Usually, you can initialise that the same way you would a plain T[N] array, but when you're dealing with a non-aggregate element type, you may need to be more explicit.