14. Operations on Arrays
Assigning Arrays and Initializer Lists
Arrays are variables containing many elements, but an array can also be seen as having a single, compound value. It is thus possible to assign one array to another array of the same type. For example:
std::vector<int> array1 = {3, 8, 2}; std::vector<int> array2 = {4, -3, 4, 8}; array2 = array1;
The last statement will make the variable array2
have
three elements, of values 3, 8, 2, in that order.
It is not allowed to assign an array to another if the types of elements do not match. For example:
std::vector<int> arrayA; std::vector<double> arrayDouble = {1, 2, 3}; arrayA = arrayDouble; //not allowed, the element type does not match arrayDouble = arrayA; //not allowed, for the same reason
Braces and their content that is used to set the initial value of an array are called an initializer list. An initializer list creates a compound value made up of given values. It is possible to use an initializer list to assign a new compound value to an entire array, like this:
arrayDouble = {9, 10, 11, 12, 13};
The initializer lists have better rules for automatic conversion. They have been introduced to the language recently, so this time the automatic conversion rules are proper. As you can see, an array of doubles can be assigned a list of integers.
It is not possible to perform assignment of an initializer list to an array if it would lose some information, for example:
std::vector<int> array3; array3 = {9, 10, 11.1, 12, 13.0}; // Error!
In this example, both the third and the
final element of the initializer list are preventing this assignment from being
allowed, as the array has elements only of type int
.