当前位置:   article > 正文

C++20中的基于范围的for循环(range-based for loop)

C++20中的基于范围的for循环(range-based for loop)

      C++11中引入了对基于范围的for循环(range-based for loop)的支持:该循环对一系列值(例如容器中的所有元素)进行操作。代码段如下:

  1. const std::vector<int> vec{ 1,2,3,4,5 };
  2. for (const auto& i : vec)
  3. std::cout << i << ", ";
  4. std::cout << std::endl;

      C++17中增加对结构化绑定(structured bingding)声明的支持。代码段如下:

  1. std::map<int, int> m{ {1,-1}, {2,-2}, {3,-3} };
  2. for (const auto& [key, value] : m)
  3. std::cout << key << "," << value << "; ";
  4. std::cout << std::endl;

      C++20中增加支持声明任意多个变量,必须以分号结尾。代码段如下:

  1. const std::vector<int> vec{ 1,2,3,4,5 };
  2. for (auto n = vec.size(), m = static_cast<size_t>(0); const auto & i : vec)
  3. std::cout << --n + i << "," << ++m << "; ";
  4. std::cout << std::endl;
  5. for (const auto vec = std::vector{ -1,-2,-3,-4,-5 }; const auto& i : vec)
  6. std::cout << i << ", ";
  7. std::cout << std::endl;

      以下为完整测试代码:

  1. int test_for_20()
  2. {
  3. const std::vector<int> vec{ 1,2,3,4,5 };
  4. // C++11
  5. for (const auto& i : vec)
  6. std::cout << i << ", ";
  7. std::cout << std::endl;
  8. // C++17
  9. std::map<int, int> m{ {1,-1}, {2,-2}, {3,-3} };
  10. for (const auto& [key, value] : m)
  11. std::cout << key << "," << value << "; ";
  12. std::cout << std::endl;
  13. // C++20
  14. for (auto n = vec.size(), m = static_cast<size_t>(0); const auto & i : vec)
  15. std::cout << --n + i << "," << ++m << "; ";
  16. std::cout << std::endl;
  17. for (const auto vec = std::vector{ -1,-2,-3,-4,-5 }; const auto& i : vec)
  18. std::cout << i << ", ";
  19. std::cout << std::endl;
  20. return 0;
  21. }

      执行结果如下图所示:

      GitHubhttps://github.com/fengbingchun/Messy_Test

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/795532
推荐阅读
相关标签
  

闽ICP备14008679号