将数组分配给数组 [英] Assign array to array

查看:51
本文介绍了将数组分配给数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在玩一些数组,但我不明白为什么这行不通.

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 = numbers; 

出现以下错误:

Error   1   error C2106: '=' : left operand must be l-value c:\users\abc\documents\visual studio 2012\projects\consoleapplication7\consoleapplication7\main.cpp 9   1   ConsoleApplication7

为什么我不能这样做?错误是什么意思?

Why can't I do like that? What does the error mean?

推荐答案

由于 C++ 与 C 的向后兼容性,数组具有多种丑陋的行为.其中一种行为是数组不可赋值.使用 std::arraystd::vector 代替.

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 <array>
...
std::array<int,5> numbers = {1,2,3};
std::array<int,5> values = {};
values = numbers;

如果由于某种原因必须使用数组,则必须通过循环或使用循环的函数复制元素,例如 std::copy

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 <algorithm>
...
int numbers[5] = {1, 2, 3};
int values[5] = {};
std::copy(numbers, numbers + 5, values);

作为旁注,您可能已经注意到我初始化 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] = {};

这篇关于将数组分配给数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆