簡體   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