Assign array to array

后端 未结 6 1017
礼貌的吻别
礼貌的吻别 2021-01-03 23:32

So I am playing around with some arrays, and I cannot figure out why this won\'t work.

int numbers[5] = {1, 2, 3};
int values[5] = {0, 0, 0, 0, 0};
values =          


        
6条回答
  •  借酒劲吻你
    2021-01-04 00:02

    Arrays have a variety of ugly behavior owing to C++'s backward compatibility with C. One of those behaviors is that arrays are not assignable. Use std::array or std::vector instead.

    #include 
    ...
    std::array numbers = {1,2,3};
    std::array values = {};
    values = numbers;
    

    If, for some reason, you must use arrays, then you will have to copy the elements via a loop, or a function which uses a loop, such as std::copy

    #include 
    ...
    int numbers[5] = {1, 2, 3};
    int values[5] = {};
    std::copy(numbers, numbers + 5, values);
    

    As a side note, you may have noticed a difference in the way I initialized the values array, simply providing an empty initializer list. I am relying on a rule from the standard that says that if you provide an initializer list for an aggregate, no matter how partial, all unspecified elements are value initialized. For integer types, value initialization means initialization to zero. So these two are exactly equivalent:

    int values[5] = {0, 0, 0, 0, 0};
    int values[5] = {};
    

提交回复
热议问题