如何在运行时使用 array<int,10> 或 array<int,4> ?

Did*_*set 4 c++ arrays for-loop stdarray

我希望我的代码根据运行时值使用数组的短版本或长版本(其中包含更多元素)。

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
}
Run Code Online (Sandbox Code Playgroud)

如上所述,有一个错误,因为三元运算符的参数不同。

我怎样才能做到这一点?

唯一的方法是声明两个分配的开始和结束迭代器。但这会导致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
}
Run Code Online (Sandbox Code Playgroud)

有没有办法编写它(也许将数组复制到向量?)以避免恢复到开始/结束版本?

eer*_*ika 6

例如,您可以使用 lambda:

auto doTheStuff = [](auto& myArray) {
    for(auto n : myArray) {
         // Do the stuff
    }
};

useShortArray ? doTheStuff(shortArray) : doTheStuff(longArray);
Run Code Online (Sandbox Code Playgroud)

或者,如果你想给它一个名字,这可以是一个模板函数。

另一种方法是使用跨度,例如std::spanC++20 中即将推出的。在这种方法中,接受不同大小数组的模板函数是 span 的构造函数。这样,使用范围的函数就不需要是模板。