我可以得到std::array<double,dof>*arr,其中dof将已知运行时

can I get std::array<double, dof> *arr, where dof will be known runtime

本文关键字:dof arr 其中 运行时 double std array 我可以 lt gt      更新时间:2023-10-16

由于某些原因,我需要以下任何一项才能工作:

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

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

有变通办法吗?或者任何其他容器?

(这是对现有代码和现有库的妥协。)

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

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

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

auto* arr_ptr = arr.data();

我想你做不到。阅读此答案了解更多信息。

只需使用std::矢量。

现在,你有这样的东西:

#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;
}