首页 > 编程语言 > 详细

C++ for 循环的5种用法

时间:2020-06-28 21:31:01      阅读:88      评论:0      收藏:0      [点我收藏+]

介绍了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;
}

 

技术分享图片

 

C++ for 循环的5种用法

原文:https://www.cnblogs.com/music-liang/p/13204979.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!