C++六种for循环

本文展示了C++中for循环的五种用法,包括传统的索引循环、迭代器循环、Qt库的foreach、std::for_each以及C++11的范围for循环。通过示例代码详细解释了如何遍历数组和字符串,帮助读者理解和记忆这些常见的循环语法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++ for 循环的5种用法。通过这里的案例,熟悉用法, 还有Qt库的foreach

for each   in
std::for_each
for  in
for :    //C++11
for

下面是例子,有时候会搞混忘记😀, 还有QT库的 foreach 中间不加空格

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <unordered_map>
#include <algorithm>
#include <QCoreApplication>
#include <QDebug>
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;
	
	//QT 库的foreach接收两个参数variable和container,
	//container是一个容器,variable相当于容器中的item, 也就是遍历容器中的每一项,
	//也是C++11新特性中的范围for的扩展
    foreach (auto i, iterable) 
    {
        qDebug() << i;
    }
    foreach (auto i , strText)
    {
        qDebug() << i;
    }
}


int main()
{
    TestFor();

    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值