Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot initialize a vector of const char*/string array with an initializer-list on declaration

Tags:

c++

c++11

Initially I started trying to initialize a vector of const char*[3] with an initilizer-list on declaration

vector<const char*[3]> v = { { "a", "b", "c" } };

And this gives the error

matrix must be initialized with a brace-enclosed initializer

I thought it might be due to the const char*, although it seemed odd, and changed it into strings

vector<string[3]> v = { { "a", "b", "c" } };

But the error persists. I tried several combinations of braces to no avail. Is it actually possible to initialize this structure on declaration with an initializer-list?

like image 771
ronaldo Avatar asked Sep 16 '18 09:09

ronaldo


1 Answers

It fails to compile because std::vector requires its T to be CopyAssignable. No matter its RHS, this statement wouldn't not compile:

vector<const char*[3]> v = { { "a", "b", "c" } }; // Error

just as this wouldn't compile either:

std::vector<const char*[3]> v;
const char* charPtrArr[3] { "a", "b", "c" };
v.push_back(charPtrArr); // Error

This is just a particular case of the fact that C-style arrays are not assignable, demonstrated in code directly by using static_assert:

static_assert(std::is_copy_assignable<const char*[3]>()); // Error

or more generally I guess:

static_assert(std::is_copy_assignable<int[]>()); // Error

If you really wanted a std::vector of arrays of size 3 holding char pointers, then this is the error-free C++11 way to go about it:

vector<array<const char*, 3>> v = { { "a", "b", "c" }, { "d", "e", "f"} };
like image 117
Geezer Avatar answered Nov 14 '22 22:11

Geezer