Std :: array C ++ 11 initializer syntax error

std :: array im getting

no match for 'operator=' in 'myarr = {1, 5, 2, 3, 4}' 

when compiling this code

 #include <iostream> #include <array> using namespace std; int main(int argc, char const *argv[]) { array<int, 5> myarr; myarr = {1,5,2,3,4}; for(auto i : myarr) { cout << i << endl; } return 0; } 

but it compiles when I do it on the same line

 array<int, 5> myarr = {1,5,2,3,4}; 

how to assign values ​​on a separate line

I need to assign values ​​in the class constructor, how can I do this?

 class myclass { myclass() { myarr = {1,2,3,4,5}; /// how to assign it // it gives errors } }; 
+1
c ++ arrays c ++ 11 std operator-keyword
source share
2 answers

Instead of one pair of curly braces, you need two.

 myarray = {{1,2,3,4,5}}; 
+6
source share

You need a temporary object.

 class myclass { myclass() { myarr = std::array<int,5>{1,2,3,4,5}; } }; 

The syntax var = { values, ... } valid only for initializers. But you are doing the task here, not initialization. What has changed in C ++ 11 is that you can now do this type of initialization for any type of class (where the corresponding constructor is defined), before it worked only on POD types and arrays.

-one
source share

All Articles