• C++遍历容器的4种方式


    定义一个map用来演示本次的遍历:

    	std::map<int, std::string> test;
    	test.insert(std::make_pair(1, "Test"));
    	test.insert(std::make_pair(2, "Product"));

    方式1:利用迭代器

    	//1.1 iterator显示声明
    	for (std::map<int, std::string>::iterator iter = test.begin(); iter != test.end(); iter++)
    	{
    		std::cout << iter->second << std::endl;
    	}
    
    	//1.2 iterator auto关键字自动推断类型
    	for (auto iter = test.begin(); iter != test.end(); iter++)
    	{
    		std::cout << iter->second << std::endl;
    	}
    

    方式2:利用for each语法

    	//2.1 for each,类型显示声明
    	for each (std::pair<int, std::string> tt in test)
    	{
    		std::cout << tt.second << std::endl;
    	}
    
    	//2.2 for each, auto关键字自动推断类型
    	for each (auto tt in test)
    	{
    		std::cout << tt.second << std::endl;
    	}
    

    方式3:利用增强型for循环

    	//3.1 增强型for循环
    	for (auto iter : test)
    	{
    		std::cout << iter.second << std::endl;
    	}
    

    for(auto a:b)中b为一个容器,效果是利用a遍历并获得b容器中的每一个值,但是a无法影响到b容器中的元素。

    for(auto &a:b)中加了引用符号,可以对容器中的内容进行赋值,即可通过对a赋值来做到容器b的内容填充。

    方式4:如果是vector容器,可以直接采用下表访问

  • 相关阅读:
    plusOne
    lengthOfLastWord
    maxSubArray
    countAndSay
    学生会管理系统-后端个人总结
    基于图结构实现地铁乘坐线路查询
    地铁线路项目简要分析
    Spring Boot 路由
    Spring Boot 项目配置的使用方法
    IDEA搭建Spring Boot项目
  • 原文地址:https://www.cnblogs.com/stonemjl/p/12619102.html
Copyright © 2020-2023  润新知