将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>"

查看:98
本文介绍了将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&lt; T,U&gt; = T [U])-从"T [U]"开始不存在合适的构造函数.到"std :: array&lt; T,U&gt;"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆