我可以得到std :: array <double,dof =“”> * arr,其中dof将被称为运行时</double,>

时间:2014-09-26 00:05:13

标签: c++ arrays

出于某种原因,我需要以下任何一项工作:

std::array<double, dof> *arr;std::array<double, dof> **arr;

我需要从输入文件或命令行获取dof。或者,经过一些计算后,我知道dof的价值。

有解决方法吗?还是其他任何容器?

(这是为了与现有代码和现有库妥协。)

2 个答案:

答案 0 :(得分:0)

我认为你不能。请阅读this回答。

只需使用std :: vector。

现在,你有这样的事情:

#include <iostream>
#include <vector>

int main ()
{
  int dof, value;
  std::cout << "How many elements?\n"; // asume dof is one
  std::cin >> dof;
  std::cout << "Which value?\n"; // asume dof is one
  std::cin >> value;
  std::vector<int> v(dof, value);

  for(std::vector<int>::const_iterator it = v.begin();
      it != v.end(); ++it) {
    std::cout << *it << " ";
  }
  std::cout << std::endl;


  return 0;
}

答案 1 :(得分:0)

模板参数必须在编译时知道。您可以改为使用std::vector

std::vector<double> arr(dof);

在任何情况下你都不需要指针。如果以后需要获取指向底层数组的指针,可以使用:

auto* arr_ptr = arr.data();