您的当前位置:首页正文

C++ - stdmap正向遍历与反向遍历的几种方式

2024-11-28 来源:个人技术集锦

文章目录

1 std::map正向遍历

1.1 for循环

#include <iostream>
#include <string>
#include <map>

int main()
{
	std::map<int, std::string> t_Map;
	t_Map[0] = "A";
	t_Map[1] = "B";
	t_Map[2] = "C";

	std::map<int, std::string>::iterator iter1;
	for (iter1 = t_Map.begin();iter1 != t_Map.end();iter1++)
	{
		std::cout << iter1->first << " : " << iter1->second << std::endl;
	}
	
	getchar();
	return 0;
}

1.2 while循环

#include <iostream>
#include <string>
#include <map>

int main()
{
	std::map<int, std::string> t_Map;
	t_Map[0] = "A";
	t_Map[1] = "B";
	t_Map[2] = "C";

	std::map<int, std::string>::iterator iter2 = t_Map.begin();
	while (iter2 != t_Map.end())
	{
		std::cout << iter2->first << " : " << iter2->second << std::endl;
		iter2++;
	}


	getchar();
	return 0;
}

2 std::map反向遍历

2.1 for循环

#include <iostream>
#include <string>
#include <map>

int main()
{
	std::map<int, std::string> t_Map;
	t_Map[0] = "A";
	t_Map[1] = "B";
	t_Map[2] = "C";

	std::map<int, std::string>::reverse_iterator iter1;
	for (iter1 = t_Map.rbegin();iter1 != t_Map.rend();iter1++)
	{
		std::cout << iter1->first << " : " << iter1->second << std::endl;
	}
	
	getchar();
	return 0;
}

2.2 while循环

#include <iostream>
#include <string>
#include <map>

int main()
{
	std::map<int, std::string> t_Map;
	t_Map[0] = "A";
	t_Map[1] = "B";
	t_Map[2] = "C";

	std::map<int, std::string>::reverse_iterator iter2 = t_Map.rbegin();
	while (iter2 != t_Map.rend())
	{
		std::cout << iter2->first << " : " << iter2->second << std::endl;
		iter2++;
	}


	getchar();
	return 0;
}

如果有兴趣可以访问我的个人站:

显示全文