c ++数组分配多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5732798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c++ array assignment of multiple values
提问by kamikaze_pilot
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?
有没有办法这样做?
采纳答案by Nawaz
There is a difference between initializationand assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
初始化和赋值是有区别的。你要做的不是初始化,而是赋值。但是在 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:
但是,在 C++0x 中,您可以这样做:
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.
当然,如果您选择使用std::vector
原始数组代替。
回答by Nawaz
You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..)
or std::copy
您必须一个一个地替换值,例如在 for 循环中或将另一个数组复制到另一个数组上,例如使用memcpy(..)
或std::copy
e.g.
例如
for (int i = 0; i < arrayLength; i++) {
array[i] = newValue[i];
}
Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.
注意确保正确的边界检查和任何其他需要进行的检查,以防止出现越界问题。
回答by sehe
const static int newvals[] = {34,2,4,5,6};
std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);