Search code examples
c++arrayssyntaxprogramming-languagesassign

How do you assign all elements of an array at once?


When you initialize an array, you can assign multiple values to it in one spot:

int array [] = {1,3,34,5,6};

... but what if the array is already initialized and I want to completely replace the values of the elements in that array in one line:

int array [] = {1,3,34,5,6};
array [] = {34,2,4,5,6};

This doesn't seem to work. Is there a way to do so?


Solution

  • There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.

    Here is what you can do:

    #include <algorithm>
    
    int array [] = {1,3,34,5,6};
    int newarr [] = {34,2,4,5,6};
    
    std::ranges::copy(newarr, array); // C++20
    // or
    std::copy(std::begin(newarr), std::end(newarr), std::begin(array)); // C++11
    // or
    std::copy(newarr, newarr + 5, array); // C++03
    

    In C++11, you can also do this:

    std::vector<int> array = {1,3,34,5,6};
    array = {34,2,4,5,6};
    

    Of course, if you choose to use std::vector instead of raw array.