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?
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"} };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With