gpt4 book ai didi

c++ - 使用 size_t 索引以相反的顺序枚举数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:08 25 4
gpt4 key购买 nike

假设我们需要以相反的顺序打印大小为 Nint 数组:

// Wrong, i is unsigned and always >= 0:
for(size_t i = N-1; i >= 0; --i){cout << data[i];}

// Correct, but uses int instead of size_t:
for(int i = N-1; i >= 0; --i){cout << data[i];}

// Correct, but requires additional operation in the loop:
for(size_t i = N; i > 0; --i){cout << data[i-1];}

// Probably the best version, but less readable.
// Is this well-defined behavior?
for(size_t i = N-1; i != (size_t)(-1); --i){cout << data[i];}

是否有更好的方法来使用 size_t 索引进行此类枚举并且无需在循环中进行额外操作?

假设 (size_t)0 - 1 给出 (size_t)(-1) 还是未定义是否有效?

最佳答案

您可以将减量移动到条件“之后”。

for(size_t i = N; i > 0;) {
--i;
cout << data[i];
}

它不像前向循环那么优雅,但它可以工作。我们在 0 处中断,所以 i 永远不会换行。

关于c++ - 使用 size_t 索引以相反的顺序枚举数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27224518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com