![](/img/trans.png)
[英]Can the dimension of std::array be read from command line arguments?
[英]How can we use std::array when the size of the array is given from the config file via command line arguments?
我正在嘗試使用大小由配置文件通過 C++ 中的命令行參數給出的std::array
。
配置看起來像這樣
100 // array size
... // other application parameters
即使在期望通過命令行參數確定數組大小的更簡單的設置中,即./main 100
,這也不起作用,因為數組大小不是在編譯時確定的。
#include <array>
int main(int argc, char** argv) {
if (argc != 2)
return 1;
int n = stoi(argv[1]);
std::array<int, n> arr;
... // do my job
}
是否有任何黑客可以使用std::array
做同樣的事情,而不是動態 STL 容器?
你不能。
如果您的尺寸在運行時給出,您需要一個動態容器。 這就是動態的定義!
如果您被禁止使用動態分配,您將必須擁有一個大的std::array
,其中可能包含許多未使用的元素以及配置文件中圖形的最大支持上限。
如果n
的允許值集在編譯時已知(例如1
、 10
或100
),您可以為這些值中的每一個生成代碼(但這可能導致代碼膨脹),然后使用if
s select 運行時的分支。 使用 C++17 折疊表達式,這個想法可以通過以下方式實現:
template<std::size_t n>
void foo_impl(/* some parameters */) {
std::array<int, n> arr;
// ...
}
template<std::size_t... ns, typename... Args>
void foo(std::size_t n, Args&&... args) {
assert(((n == ns) || ...));
((n == ns && (foo_impl<ns>(std::forward<Args>(args)...), true)), ...);
}
const std::size_t n = /* run-time value */;
foo<1, 10, 100>(n, /* some parameters */);
這里n == ns && expr
是一個眾所周知的“hack”,僅當條件n == ns
評估為true
時才評估expr
。
std::array
要求您在編譯時知道大小。 做你所說的唯一方法是讓你的程序編譯另一個具有正確大小值的程序並執行它。
這里最好的選擇可能是使用像std::vector
這樣的動態大小容器。
是否有任何黑客可以使用 std::array 做同樣的事情,而不是動態 STL 容器?
不,沒有這樣的黑客。 只能使用具有編譯時間常數大小的std::array
。
如果您想要動態大小,那么您需要使用動態數組(或其他一些動態數據結構)。
無法在運行時定義std::array
長度。
您可以改用std::vector
。
它的行為(有點)像一個數組,只是它為堆內的 memory 分配了塊。
你可能會是這樣的:
int n = stoi(argv[1]);
std::vector<int> my_data{};
my_data.resize(n); //Allocates n elements
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.