Giz*_*zmo 18 c c++ arrays c++11
我试图将C数组分配给C++ std :: array.
我怎么做,最干净的方式,没有不需要的副本等?
做的时候
int X[8];
std::array<int,8> Y = X;
Run Code Online (Sandbox Code Playgroud)
我得到一个编译错误:"没有合适的构造函数存在".
jua*_*nza 21
没有从plain数组转换为std::array,但您可以将元素从一个复制到另一个:
std::copy(std::begin(X), std::end(X), std::begin(Y));
Run Code Online (Sandbox Code Playgroud)
这是一个有效的例子:
#include <iostream>
#include <array>
#include <algorithm> // std::copy
int main() {
int X[8] = {0,1,2,3,4,5,6,7};
std::array<int,8> Y;
std::copy(std::begin(X), std::end(X), std::begin(Y));
for (int i: Y)
std::cout << i << " ";
std::cout << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 17
C++20 有std::to_array函数
所以,代码是
int X[8];
std::array<int, 8> Y = std::to_array(X);
Run Code Online (Sandbox Code Playgroud)
https://godbolt.org/z/Efsrvzs7Y