![](/img/trans.png)
[英]How can we use std::array when the size of the array is given from the config file via command line arguments?
[英]Can the dimension of std::array be read from command line arguments?
我有一個 C++ 代碼,我決定使用std::array
而不是std::vector
並且我希望從命令行讀取數組的大小。
在實踐中,這可以用下面的片段來總結
#include <iostream>
#include <array>
#include <sstream>
int main(int argc, char* argv[]){
std::size_t my_size;
{
std::istringstream is{argv[1]};
is >> my_size;
}
std::cout << my_size<<std::endl;
std::array<int,my_size> a;
return 0;
}
編譯器給出以下錯誤,這是由於在編譯時必須知道my_size
。
錯誤:“my_size”的值在常量表達式中不可用
14 | std::array<int,my_size>一個;
有沒有辦法讓std::array
的大小從命令行給出? 還是我絕對應該使用其他容器? 作為堆上的動態 arrays 或std::vector
?
特別是類型和 arrays 大小必須在編譯時已知,因此答案是:否。
您可以實現一些從運行時值到編譯時常量的映射。 沿線的東西
size_t size;
std::cin >> size;
if (size == 10) {
std::array<int,10> x;
// use x
} else if (size == 20) [
std::array<int,20> y;
// use y
}
然而,這是非常有限的用途,因為x
和y
是不同的類型。 當大小僅在運行時已知時,使用std::vector
會更容易。
您可以將相對較小的尺寸轉換為常量。 在C++17中可以這樣解決。
#include <iostream>
#include <array>
#include <sstream>
#include <utility>
constexpr std::size_t MAX_SIZE = 10;
template <class T, class F, T... I>
bool to_const(T value, F&& fn, std::integer_sequence<T, I...>) {
return (
(value == I && (fn(std::integral_constant<T, I>{}), true))
|| ... // or continue
);
}
template <class T, class F>
bool to_const(T value, F&& fn) {
return value <= MAX_SIZE &&
to_const(value, fn, std::make_integer_sequence<T, MAX_SIZE + 1>{});
}
int main(int argc, char* argv[]){
std::size_t my_size;
{
std::istringstream is{argv[1]};
is >> my_size;
}
std::cout << my_size<<std::endl;
bool found = to_const(my_size, [](auto N)
{
std::array<int, N> a;
});
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.