C++_12——新特性(基于范围的for循环)

C++_12——新特性(基于范围的for循环)

  这一系列文章的目的是在学习了C++基础后,继续补充一些C++基础和进阶的知识点,包括C++11的相关内容。
以C++11标准为基础。

  1. main.cpp
#include "pch.h"
#include <iostream>
#include <vector>
#include <map>
#include <set>

#include "Range.h"

const std::vector<int> getVector(const std::vector<int> &u){
	std::cout << "get vector" << std::endl;
	return u;
}

int main(){
	std::vector<int> test = { 1,2,3 };
	std::map<int, int> test2 = { {1,2},{2,4} };
	std::set<int> test3 = { 1,3,4,5,8 };

//range-based for 基本用法
	//遍历向量容器
	for (auto each : test){
		std::cout << " each: " << each << std::endl;
	}

	//修改遍历的容器,要以引用的形式,否则实现的是值传递
	for (auto each : test){
		std::cout << " each++ : " << each++ << std::endl;
	}

	for (auto each : test){
		std::cout << " after & each++ : " << each << std::endl;
	}

	for (auto& each : test){
		std::cout << " before & each++ : " << each++ << std::endl;
	}
	for (auto each : test){
		std::cout << " after & each++ : " << each << std::endl;
	}

	//另一种容器:map
	for (auto each : test2){
		//在遍历容器的时候,auto自动推导的类型是容器的value_type类型,而不是迭代器,而map中的value_type是std::pair,
		//也就是说val的类型是std::pair类型的,因此需要使用val.first,val.second来访问数据。 
		std::cout << each.first << each.second << std::endl;
	}

//遍历函数返回的容器
	for (auto each : getVector(test)){
		std::cout << "getVector(test): " << each << std::endl;
	}

//修改容器大小
	for (auto each : test3){
		std::cout << "change iterator set: " << each << std::endl;
		test3.insert({ 2,7 });
	}

	for (auto each : test){
		std::cout << "change iterator vector: " << each << std::endl;

		test.push_back(1);			//不报错但数错
	}

//自定义range和iterator
	for (auto each : Range(1,5)){
		std::cout << "Range(1,5): " << each << std::endl;
	}

    std::cout << "Hello World!\n"; 
}

  1. Range.h
	//range给出iterator的起止位置,iterator负责迭代结果
	//myIterator,自定义的迭代器需要实现运算符的重载,特别是迭代规则operator++()
	class myIterator{
	public:
		myIterator(int value) :_value(value) {};
	
		bool operator!=(const myIterator& other) const{
			return this->_value != other._value;
		}
	
		const int & operator*()//解引用{
			return _value;
		}
	
		int& operator++(){
			return ++_value;
		}
	
	private:
		int _value;
	};
	
	//Range要实现begin()和end()两个函数,以获取迭代的起止位置
	class Range{
	public:
		Range(int begin, int end) :_begin(begin), _end(end) {};
		~Range() {};
	
		myIterator begin() {
			return myIterator(_begin);
		}
	
		myIterator end() {
			return myIterator(_end);
		}
	
	private:
		int _begin;
		int _end;
	};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值