C++11 引入了一种新的 for 循环,让对一系列值(如数组包含的值)进行操作的代码更容易编写和 理解。

    1. #include <iostream>
    2. #include <string>
    3. using namespace std;
    4. int main()
    5. {
    6. // 整型
    7. int someNums[] = {1,101,-1,40,2040};
    8. for (auto elemente: someNums){
    9. cout << elemente << " ";
    10. }
    11. cout << endl;
    12. // 字符
    13. char charArray[] = {'h','e','l','l','o'};
    14. for (auto aChar: charArray){
    15. cout << aChar << ' ';
    16. }
    17. cout << endl;
    18. //字符串
    19. string strArray = {"hello"};
    20. for (auto strElement: strArray){
    21. cout << strElement << ' ';
    22. }
    23. cout << endl;
    24. }

    值得注意的是
    如果需要修改 数组之中的elemente

    1. #include <iostream>
    2. #include <string>
    3. using namespace std;
    4. int main()
    5. {
    6. // 整型 修改引用值
    7. int someNums[] = {1,101,-1,40,2040};
    8. for (auto elemente: someNums){
    9. cout << elemente << " ";
    10. }
    11. cout << endl;
    12. for (int &elemente: someNums){
    13. elemente *=2;
    14. }
    15. for (auto elemente: someNums){
    16. cout << elemente << " ";
    17. }
    18. cout << endl;
    19. // 整型 不修改引用值
    20. int someNums[] = {1,101,-1,40,2040};
    21. for (auto elemente: someNums){
    22. cout << elemente << " ";
    23. }
    24. cout << endl;
    25. for (int elemente: someNums){
    26. elemente *=2;
    27. }
    28. for (auto elemente: someNums){
    29. cout << elemente << " ";
    30. }
    31. cout << endl;
    32. }