You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

解决运行时选择不同长度std::array的遍历问题

Hey there! Let's tackle this problem where you want to pick between a short and long std::array at runtime and iterate over it cleanly without messing around with separate begin/end iterators. Your original code hits a snag because the two std::array types have different sizes, making them incompatible for the ternary operator. Here are a couple of cleaner alternatives:

方案1:复制到std::vector(简单直接)

If you don't mind a small copy overhead (totally acceptable for small arrays like your examples), you can convert either array to a std::vector on the fly. This gives you a uniform type to work with, perfect for range-based for loops:

#include <array>
#include <vector>

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};
bool useShortArray = /* 你的运行时判断条件 */;

std::vector<int> myArray = useShortArray 
    ? std::vector<int>(shortArray.begin(), shortArray.end()) 
    : std::vector<int>(longArray.begin(), longArray.end());

for (auto n : myArray) {
    // 在这里执行你的操作
}

方案2:使用std::span(零开销,C++20+)

For a more efficient approach with no data copying, use std::span (available in C++20 and later). A span acts as a lightweight view over a contiguous sequence of elements, so it can wrap either array without duplicating data. This keeps your code clean and efficient:

#include <array>
#include <span>

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};
bool useShortArray = /* 你的运行时判断条件 */;

std::span<const int> myArray = useShortArray 
    ? std::span(shortArray) 
    : std::span(longArray);

for (auto n : myArray) {
    // 在这里执行你的操作
}

This is my favorite option because it maintains the original array's const-ness, avoids unnecessary copies, and lets you use the range-based for loop just like you wanted in your initial code.

为什么这些方案比单独用迭代器好?

Your original iterator-based approach works, but it's more verbose and easy to make mistakes (like forgetting to update both begin and end if you change the logic). The alternatives above keep your code readable and aligned with modern C++ practices.

内容的提问来源于stack exchange,提问作者Didier Trosset

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:14:17