c++编程---c++11 for

本文介绍C++11中新增的for range循环的使用方法,展示了如何使用这种更简洁的语法来遍历字符串、数组、vector、list和map等数据结构,提高代码的可读性和开发效率。

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

前言

C++11 增加了很多C++程序员期待已久的for range循环, 使用for range 可以让代码变得更简洁,开发效率更高

使用场景

1 遍历字符串

    // string
    std::string strTest("Hello World"); 
    // before
    for(std::string::iterator iter = strTest.begin(); iter != strTest.end(); iter++)
    {
        std::cout << *iter << std::endl;
    }
    // c++ 11
    for(auto ch : strTest)
    {
        std::cout <<ch << std::endl;
    }

2 遍历数组

不用知道数组容器的大小,也可方便的遍历数组。

 // array
    int arr[] = {1,2,3,4};
    int arrLen = 4;
    // before
    for(int loop = 0; loop < arrLen; loop ++)
    {
        std::cout << arr[loop] << std::endl;
    }
    // c++11
    for(auto loop : arr)
    {
        std::cout << loop <<  std::endl;
    }

3 遍历vector

// vector
    std::vector<std::string> mvec {"I", "like", "china"};
    // before
    for(int loop = 0; loop < mvec.size(); loop++)
    {
        std::cout << mvec[loop] << std::endl;
    }
    // c++11
    for(auto it : mvec)
    {
        std::cout << it << std::endl;
    }

4 遍历list

    // list
    std::list<std::string> mlist {"I", "am", "a", "goodboy"};
    // before
    for(std::list<std::string>::iterator iter = mlist.begin(); iter != mlist.end(); iter++)
    {
        std::cout << *iter << std::endl;
    }
    // c++11
    for(auto it: mlist)
    {
        std::cout << it << std::endl;
    }

5 遍历map

    // map
    std::map<int, std::string> mMap = {{1, "c++"}, {2, "jave"}, {3, "python"}, {4, "go"}};
    // before
    for(std::map<int, std::string>::iterator iter = mMap.begin(); iter != mMap.end(); iter++)
    {
        std::cout << iter->first << std::endl;
        std::cout << iter->second << std::endl;
    }
    // c++11
    // 遍历map返回的是pair变量,不是迭代器。
    for(auto it:mMap)
    {
        std::cout << it.first << std::endl;
        std::cout << it.second << std::endl;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值