C++ for 循环的5种用法

介绍了C++ for 循环的5种用法。通过这里的案例,也可以熟悉对string 容器的使用。可以通过[] 来访问string 对象。 

for each

std::for_each

for  in

for : 

for 

 

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>
using namespace std;

void TestFor()
{
    int nArray[] = { 5,4,3,2,1,666,777 };
    std::vector<int> vecNum(nArray, nArray + 6);
    string strText = "ABCDEFGHIJKLMN";

    //第1种用法
    cout << "========for 1:" << endl;
    for (int i = 0; i < vecNum.size(); ++i)
    {
        printf("(%d,%d) ", i, vecNum[i]);
    }
    cout << endl;
    for (int i = 0; i < strText.size(); ++i)
    {
        printf("(%d,%c), ", i, strText[i]);
    }
    cout << endl << endl;


    //第2种用法
    cout << "========for 2:" << endl;
    for (std::vector<int>::iterator it = vecNum.begin(); it != vecNum.end(); ++it)
    {
        printf("%d, ", *it);
    }
    cout << endl;
    for (auto it = strText.begin(); it != strText.end(); ++it)
    {
        printf("%c, ", *it);
    }
    cout << endl << endl;


    //第3种用法
    cout << "========for 3: for each" << endl;
    for each(auto item in vecNum)
    {
        printf("%d, ", item);
    }
    cout << endl;
    for each(auto item in strText)
    {
        printf("%c, ", item);
    }
    cout << endl << endl;


    //第4种用法
    cout << "========for 4: std::for_each  需要包含<algorithm>" << endl;
    std::for_each(vecNum.begin(), vecNum.end(), [](int item) {
        printf("%d, ", item);
    });
    cout << endl;
    std::for_each(strText.begin(), strText.end(), [](int item) {
        printf("%c, ", item);
    });
    cout << endl << endl;



    //第5种用法
    cout << "========for 5: " << endl;
    for (auto item : vecNum)
    {
        printf("%d, ", item);
    }
    cout << endl;
    for (auto item : strText)
    {
        printf("%c, ", item);
    }
    cout << endl << endl;

}

int main()
{
    TestFor();

    return 0;
}

 

 

posted @ 2020-06-28 20:51  He_LiangLiang  阅读(11479)  评论(0编辑  收藏  举报