1

How to initialize an array, out of the length definition line?

int a[5]; //this line fixed, only state the array name and size
a = {1,2,3,4,5};  //error: Array type 'int [5]' is not assignable
a[] = {1,2,3,4,5};//error: expected expression

What's the correct way (use one line) to fill {1,2,3,4,5} into a[5] out of the definition line?

5
  • 2
    Can't be done, I'm afraid. Arrays are extremely simple, limited tools. Is std::array an available option? Dec 8, 2020 at 2:43
  • You can assign to 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 it const if it won't change.
    – tadman
    Dec 8, 2020 at 2:46
  • @user4581301, yes.
    – Xuhang
    Dec 8, 2020 at 2:49
  • An array is NOT an lvalue. Dec 8, 2020 at 2:57
  • 1
    The correct way would be: int a[5] = {1,2,3,4,5}; Though I would probably use: int a[] = {1,2,3,4,5}; Dec 8, 2020 at 3:04

2 Answers 2

3

'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.

2

How to initialize an array, out of the length definition line?

Then it can't be an initialization again. (And raw arrays can't be assigned directly, while std::array or std::vector could.)

(emphasis mine)

Initialization of a variable provides its initial value at the time of construction.

You can use std::iota (or std::fill etc.) to fill the array, e.g.

int a[5]; // default initialization
std::iota(std::begin(a), std::end(a), 1); // fill the array as {1, 2, 3, 4, 5}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.