如果遍历map中最后一个元素rbegin(),end(),rend()

  • Post author:
  • Post category:其他


#include "stdafx.h"


#include <iostream>
#include <map>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	map<char,int> mymap;

	mymap['b'] = 100;
	mymap['a'] = 200;
	mymap['c'] = 300;
	map<char,int>::iterator it=mymap.begin();
	// show content:
	for (it; it!=mymap.end(); ++it)
		std::cout << it->first << " => " << it->second << '\n';
	//正确做法
	 //输出map中的最后一个元素
	map<char,int>::reverse_iterator iter = mymap.rbegin(); //返回最后一个元素
	/*mymap.end();
	mymap.rend();
	*/
	if (iter != mymap.rend())
	{
		std::cout << iter->first << " => " << iter->second << '\n';
	}

	//错误做法
	 map<char,int>::iterator iter2 = mymap.end(); //
	 //如果这样直接用会导致崩溃 
	 std::cout << iter2->first << " => " << iter2->second << '\n';
	if (iter2 != mymap.end())
	{
		std::cout << iter2->first << " => " << iter2->second << '\n';
	}

	/*mymap.end();
	mymap.rend();
	这两个函数只是标记找没找到 不是返回最后一个元素
	输出最后一个元素一定要切记
	Return iterator to end
	Returns an iterator referring to the past-the-end element in the map container.

	The past-the-end element is the theoretical element that would follow the last element in the map container. 
        It does not point to any element, and thus shall not be dereferenced.

	Because the ranges used by functions of the standard library do not include the element pointed by their closing iterator,
        this function is often used in combination with map::begin to specify a range including all the elements in the container.

	If the container is empty, this function returns the same as map::begin.
	*/
	return 0;
}



版权声明:本文为jangdong原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。