Reputation: 480
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?
Upvotes: 5
Views: 2410
Reputation: 5710
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"} };
Upvotes: 7
Reputation: 37607
Problem is that C-style array can't be passed by copy or moved in function argument. As a result this code will not work
vector<const char*[3]> v;
const char* item[3] { "a", "b", "c" };
v.push_back(item); // will not compile
https://wandbox.org/permlink/LumvUzPnYWew7uMu
Basically this is the same problem, but initialization list is involved.
C++11 give you simple solution for your problem:
vector<array<const char*, 3>> v { { "a", "b", "c" }, { "d", "e", "f"} };
https://wandbox.org/permlink/IHNoSrH9BWV1IUoQ
Upvotes: 4