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

5

我有一段如下的代码:

int n;

int get_the_number();
void some_computations();

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

     return(0);
}
  • The get_the_number function get some input and returns the integer n, which after its call will not be modified.

  • In the some_computation function there is the following code

    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;

但我遇到了一个错误:数组的大小必须是常量。是否有方法可以避免这个问题发生? 非常感谢。
2个回答

12

std::array 需要在编译时知道大小,这与你的代码不适用。因此,除非get_the_number()能够返回一个constexpr,否则你不能简单地在此处用std::array替换std::vector

constexpr int get_the_number() { return 42; }

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

但是在您的情况下,假设int get_the_number()获取一个在运行时确定的数字。


看起来我打字不够快。 :) - Barney Szabolcs
非常感谢快速明确的回答。在此之前我并不知道constexpr:我还有很多东西需要学习! - 888

5
如果您想利用数组长度是运行时常量的事实来提高效率,则需要使用std::vector ::reserve预先保留必要的空间,以避免向量增长时的任何重新分配——这将使其几乎与数组一样快。请注意保留HTML标记。
my_array.reserve(get_the_number());
some_computations()

如果数组是函数内部的局部变量,可以将数字作为参数传入。


std::vector::reserve不如std::array快的原因是它会在堆上分配内存,而不是栈上。为std::vector提供一个栈分配器可能会使其接近于std::array,但需要进行基准测试。 - Ricky65

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接