C++ 新特性区间for

本文详细介绍了C++中的迭代器遍历和范围for循环的使用,包括正常迭代器遍历的方式以及简化版的区间for循环。在动态添加元素时,迭代器可以正确遍历,而范围for循环则不会包含新增元素。同时展示了map容器中key和value的遍历及其修改特性。
摘要由CSDN通过智能技术生成
#include <iostream>
#include <vector>
#include <map>
void test1()
{
    std::vector<int> array = {1, 2, 3, 4, 5};
    // 正常的遍历方式是,通过迭代器,由于每次都会判断是否end,在动态添加元素时,可以正常遍历
    for (auto it = array.begin(); it != array.end(); ++it)
    {
        std::cout<<*it<<std::endl;
    }

    // 使用区间for简化迭代,类似python用法,it是元素本身不是指针,范围遍历,array只会获取一次size后进行for遍历,所以动态添加元素不会遍历到
    for (auto it : array)// read only
    {
        std::cout<<it<<std::endl;
    }

    for (auto &it : array)// read/write
    {
        ++it;//可以对元素值进行赋值操作
        std::cout<<it<<std::endl;
    }
    for (auto it : array)// read only
    {
        std::cout<<it<<std::endl;
    }
	// 若果是stl模板中的map容器
	std::map<int, int> mp;
	mp.insert(std::make_pair<int,int>(1,2));
	mp.insert(std::make_pair<int,int>(2,3));
	for (auto& it: mp)
	{
		std::cout<<it.first<<std::endl;// key值不能被修改,是常量
		std::cout<<it.second++<<std::endl;// value可以被修改
	}
}
int main()
{
    test1();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值