我想从我的函数返回一个多维std :: array。返回数组的大小应由输入参数的大小决定。 类似的东西:
std::array<std::array<unsigned int, n>, n> foo(std::vector<int> vec){
unsigned int n = vec.size;
std::array<std::array<unsigned int, n>, n> result;
return result;
}
如果没有恼人的额外模板参数,解决这个问题会很好。 std :: vector而不是std :: array似乎没有像nd(未确定的)项目那样直接初始化为std :: array(没有显式初始化)。怎么能成为可能呢?谢谢!
答案 0 :(得分:2)
您可以使用其c来创建n
大小为std::vector
n
个std::vector
的{{1}},即:
std::vector<std::vector<unsigned int>> result(n, std::vector<unsigned int>(n, 0));
注意:根据cppreference.com,上面std::vector
s c&tor; tor的示例中使用的第二个参数是针对要创建的每个项目的值:c&#39; tor signature :
vector( size_type count, const T& value, const Allocator& alloc = Allocator());
。
答案 1 :(得分:2)
首先需要知道的是std::array
的大小在编译时是固定的,因为来自cppreference sais的documentation:
std :: array是一个封装固定大小数组的容器。
此容器是一种聚合类型,其语义与a相同 struct持有C风格的数组T [N]作为其唯一的非静态数据 构件。
如果n
来自std::cin
或来自命令行参数(或编译时间之外的任何类型的输入),则编译器无法推断出类型,因此它将抛出错误。
最明智的做法是使用std::vector
,您可以这样做:
std::vector<std::vector<unsigned int>> foo(std::vector<int> vec){
unsigned int n = vec.size();
std::vector<std::vector<unsigned int>> result(n, std::vector<unsigned int>(n));
return result;
}
使用向量的大小构造函数初始化每个向量。
答案 2 :(得分:0)
尝试使用Boost.MultiArray。它允许您创建具有任意内容类型的内容的多维数组。我已经使用过它(boost :: multi_array_ref部分更具体),它的效果非常好。一个重要的特性是能够创建数组views(以及基于视图的切片)。