我希望我的代码根据运行时值使用数组的短版本或长版本(其中包含更多元素)。
constexpr std::array<int, 10> longArray{0,1,2,3,4,5,6,7,8,9};
constexpr std::array<int,4> shortArray{0,3,6,9};
auto const& myArray = useShortArray ? shortArray : longArray;
for( auto n : myArray ) {
// Do the stuff
}
如上所述,有一个错误,因为三元运算符的参数不同。
我怎样才能做到这一点?
唯一的方法是声明两个分配的开始和结束迭代器。但这导致使用旧的
for
在迭代器上,并且需要在 for
中的每次使用时取消引用迭代器堵塞。auto const& myBegin = useShortArray ? shortArray.begin() : longArray.begin();
auto const& myEnd = useShortArray ? shortArray.end() : longArray.end();
for( auto it = myBegin ; it != myEnd ; ++it ) {
// use *it
}
有没有办法编写它(也许将数组复制到 vector ?)以避免恢复到开始/结束版本?
最佳答案
例如,您可以使用 lambda:
auto doTheStuff = [](auto& myArray) {
for(auto n : myArray) {
// Do the stuff
}
};
useShortArray ? doTheStuff(shortArray) : doTheStuff(longArray);
或者,如果你想给它一个名字,这可以是一个模板函数。
另一种方法是使用span,比如即将推出的
std::span
在 C++20 中。在这种方法中,接受不同大小数组的模板函数是 span 的构造函数。这样,使用范围的函数就不需要是模板。
关于c++ - 如何在运行时使用 array<int,10> 或 array<int,4> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59411311/