繁体   English   中英

用'std :: array`替换`std :: vector`

[英]Replace `std::vector` with `std::array`

我有一个代码如下:

int n;

int get_the_number();
void some_computations();

int main()
{
     n = get_the_number();
     some_computations()

     return(0);
}
  • get_the_number函数得到一些输入并返回整数n ,它在调用后不会被修改。

  • some_computation函数中有以下代码

     std::vector<my_struct> my_array; for(int i=0; i<n; i++) { my_struct struct_temp; // fill struct_temp; my_array.push_back(struct_temp); } 

问题:由于my_array的大小是先验已知的,是否可以用std::array替换std::vector 而且,在肯定的情况下,我应该期望在效率方面获得收益吗?

我试图用。替换矢量声明

 std::array<my_struct,n> my_array;

但是我得到一个错误:数组的大小必须是常量。 有没有办法避免它?

非常感谢你。

std::array需要知道编译时的大小,这不适用于您的代码。 所以不,你不能简单地用std::array替换std::vector ,除非get_the_number()可以返回constexpr例如。

constexpr int get_the_number() { return 42; }

int main()
{
  std::array<int, get_the_number()> a;
}

但是大概在你的情况下int get_the_number()获得在运行时确定的数字。

如果你想使用你的数组长度是运行时常量提高效率的事实,你想要做的是使用std::vector::reserve提前保留必要的空间以保存任何重新分配为向量增长 - 这应该使它几乎像array一样快。

my_array.reserve(get_the_number());
some_computations()

或者,如果数组是函数的本地数组,则将数字作为参数传入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM