将 C 数组分配给 C++ 的 std::array?(std::array<T,U> = T[U]) - “T [U]"中不存在合适的构造函数;到“std::array<T,U>" [英] Assign C array to C++'s std::array? (std::array<T,U> = T[U]) - no suitable constructor exists from "T [U]" to "std::array<T,U>"
本文介绍了将 C 数组分配给 C++ 的 std::array?(std::array<T,U> = T[U]) - “T [U]"中不存在合适的构造函数;到“std::array<T,U>"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将 C 数组分配给 C++ std::array.
I am trying to assign a C array to a C++ std::array.
我该如何做到这一点,以最干净的方式并且不制作不需要的副本等?
How do I do that, the cleanest way and without making unneeded copies etc?
什么时候做
int X[8];
std::array<int,8> Y = X;
我收到编译器错误:不存在合适的构造函数".
I get an compiler error: "no suitable constructor exists".
推荐答案
没有从普通数组到 std::array
的转换,但是您可以将元素从一个复制到另一个:
There is no conversion from plain array to std::array
, but you can copy the elements from one to the other:
std::copy(std::begin(X), std::end(X), std::begin(Y));
这是一个工作示例:
#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;
}
这篇关于将 C 数组分配给 C++ 的 std::array?(std::array<T,U> = T[U]) - “T [U]"中不存在合适的构造函数;到“std::array<T,U>"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文