Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ array assignment of multiple values

so 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

so

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

doesn't seem to work...

is there a way to do so?

like image 573
kamikaze_pilot Avatar asked Apr 20 '11 15:04

kamikaze_pilot


People also ask

Can you assign multiple variables at once in C?

If your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

How do you assign values to an array?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

Can an array be assigned in C?

You can do array assignment within structs: struct data { int arr[10]; }; struct data x = {/* blah */}; struct data y; y = x; But you can't do it directly with arrays.


1 Answers

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::copy(newarr, newarr + 5, array); 

However, in C++0x, you can 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.

like image 106
Nawaz Avatar answered Sep 20 '22 17:09

Nawaz