c++ - 迭代无符号整数的所有值的最漂亮方法

标签 c++ c++11 iteration

我想迭代一个整数的所有可能值。此代码不起作用,因为终止条件永远不会变为假:

for (uint32_t i = 0; i <= 0xFFFFFFFF; i++)
    std::cout << i << std::endl;

我想出了这个:

auto loopBody = [](uint32_t value)
{
    std::cout << value << std::endl;
};

uint32_t last = 0xFFFFFFFF;
for (uint32_t i = 0; i < last; i++)
    loopBody(i);

loopBody(last);

虽然它相当丑陋。有没有更好的方法来做到这一点?

最佳答案

我会用这样的东西:

uint32_t i = 0;
do
{
    // Your code here.
    i++;
}
while (i != 0);

我个人认为它比涉及 std::numeric_limits 的解决方案更优雅。


正如@NicosC 所说,请记住,您不应该对有符号 整数做同样的事情,因为有符号溢出是未定义的行为。

关于c++ - 迭代无符号整数的所有值的最漂亮方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36239857/

相关文章:

c++ - 如何在编译时检查类是否具有继承函数?

c++ - 随机访问迭代器到 char 数组

c++ - 给定 cbegin()、cend(),为什么没有 cfront()、cback()、cfind()、...?

c++ - 在 C++0x 中创建静态类型变体

python - 我需要帮助迭代列表列表,通过一个函数

java - 并发修改异常 : adding to an ArrayList

python - 将此函数从递归转换为迭代

C++ : declaring in if/else : var not declared in this scope

c++ - 在没有读取权限的情况下返回大小文件c++

c++ - 从父命名空间重载类型