分配在阵列 [英] Assign array to array

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

问题描述

所以我用一些阵列玩弄了,我想不通为什么这是行不通的。

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 ::阵列的std ::矢量代替。

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 ::复制

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);

作为一个方面说明,你可能已经注意到我初始化阵列方式的差异,简单地提供一个空的初始化列表。我靠从说,如果你以总提供一个初始化列表,无论怎么分,所有的不确定因素是值初始化标准的规则。对于整数类型,值初始化表示初始化为零。所以,这两个是完全等效的:

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天全站免登陆