在C ++中,是否可以直接从另一个数组初始化数组?

时间:2022-06-20 21:28:21

In C++, is it possible to initialize a built-in array directly from another? As far as I know, one can only have an array and then copy/move each element from another array to it, which is some kind of assignment, not initialization.

在C ++中,是否可以直接从另一个初始化内置数组?据我所知,一个人只能有一个数组,然后将每个元素从另一个数组复制/移动到它,这是某种赋值,而不是初始化。

2 个解决方案

#1


2  

Arrays have neither the copy constructor nor the copy assignment operator. You can only copy elements from one array to another element by element.

数组既没有复制构造函数也没有复制赋值运算符。您只能按元素将元素从一个数组复制到另一个元素。

Character arrays can be initialized by string literals. Or strings can be copied using standard C functions like strcpy, strncpy, memcpy declared in header <cstring>.

字符数组可以通过字符串文字初始化。或者可以使用标准C函数复制字符串,例如在头文件 中声明的strcpy,strncpy,memcpy。

For other arrays you can use for example standard algorithms std::copy, std::copy_if, std::transform declared in header <algorithm>.

对于其他数组,您可以使用标头算法std :: copy,std :: copy_if,std :: transform在header 中声明。

Otherwise you can use either standard container std::array or std::vector that allow to assign one object of the type to another object of the same type or create one object from another object.

否则,您可以使用标准容器std :: array或std :: vector,它允许将该类型的一个对象分配给另一个相同类型的对象,或者从另一个对象创建一个对象。

#2


4  

That is one of the new features of the std::array in C++ 11.

这是C ++ 11中std :: array的新特性之一。

std::array <int, 5> a = {1, 2, 3, 4, 5};
std::array <int ,5> b = a;

The latter copies the array a into b.

后者将数组a复制到b中。

#1


2  

Arrays have neither the copy constructor nor the copy assignment operator. You can only copy elements from one array to another element by element.

数组既没有复制构造函数也没有复制赋值运算符。您只能按元素将元素从一个数组复制到另一个元素。

Character arrays can be initialized by string literals. Or strings can be copied using standard C functions like strcpy, strncpy, memcpy declared in header <cstring>.

字符数组可以通过字符串文字初始化。或者可以使用标准C函数复制字符串,例如在头文件 中声明的strcpy,strncpy,memcpy。

For other arrays you can use for example standard algorithms std::copy, std::copy_if, std::transform declared in header <algorithm>.

对于其他数组,您可以使用标头算法std :: copy,std :: copy_if,std :: transform在header 中声明。

Otherwise you can use either standard container std::array or std::vector that allow to assign one object of the type to another object of the same type or create one object from another object.

否则,您可以使用标准容器std :: array或std :: vector,它允许将该类型的一个对象分配给另一个相同类型的对象,或者从另一个对象创建一个对象。

#2


4  

That is one of the new features of the std::array in C++ 11.

这是C ++ 11中std :: array的新特性之一。

std::array <int, 5> a = {1, 2, 3, 4, 5};
std::array <int ,5> b = a;

The latter copies the array a into b.

后者将数组a复制到b中。