我正在尝试将 C 数组分配给 C++ std::array。
我该如何做到这一点,最干净的方式并且不制作不需要的拷贝等?
什么时候做
int X[8];
std::array<int,8> Y = X;
我得到一个编译器错误:“不存在合适的构造函数”。
最佳答案
没有从普通数组到std::array
的转换,但是您可以将元素从一个复制到另一个:
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 数组分配给 C+ +'s std::array? (std::array<T,U> = T[U]) - no suitable constructor exists from "T [U ]"to "std::array<T,U>",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26219721/