c++ - 如何在运行时使用 array<int,10> 或 array<int,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
}

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

我怎样才能做到这一点?

唯一的方法是声明两个分配的开始和结束迭代器。但这导致使用旧的 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/

相关文章:

c++ - 为什么这两个打印整数二进制表示的函数具有相同的输出?

c - 插入和弹出功能

c - 错误: used struct type value where scalar is required for(;*ptr;ptr++)

c++ - 对于循环窃听?

c++ - 在 C++ 中使用二维数组进行循环

c++ - OpenAcc标准中内核与并行指令之间的区别

c++ - 将 LPCWSTR 转换为 LPCSTR

c++ - 打印字符串数组元素时 VS 中止 - C++

mysql - php回显问题

java - 如何将一个数组复制到另一个已经有数据的数组中?