'Old-style' arrays in C++ cannot be assigned data en bloc, but they can be initialized when first declared, as you have pointed out.
However, the std::array
container provided by the STL does allow its data block to be reassigned (with some caveats):
#include <iostream>
#include <array>
int main()
{
std::array<int,5> a;
// Some code that does someting ...
a = { 1,2,3,4,5 }; // Now we can ASSIGN one array (a constant) to our variable
// Show the data ...
for (auto i : a) std::cout << i << " ";
std::cout << std::endl;
a = { 10, 20, 30 }; // Reassign only PART. But note: the rest will be zero-padded
for (auto i : a) std::cout << i << " ";
std::cout << std::endl;
return 0;
}
In the above example, you can use the a
variable (once you have data in it) in much the same way as with a 'plain' array, such as using the []
indexing operator to read/write any of its elements. Further, you can also copy entire arrays of this type.
std::array
an available option?std::vector
, but not this way, as it inherits from C which did not have that capability either. Tip: Do it on one line. Do itconst
if it won't change.int a[5] = {1,2,3,4,5};
Though I would probably use:int a[] = {1,2,3,4,5};