map容器的大小和交换

2021-03-02 15:43:02 浏览数 (1)

函数原型:

代码语言:javascript复制
#include<iostream>
using namespace std;
#include<map>
void print(map<int, int>& m1)
{
	for (map<int, int>::iterator it = m1.begin(); it != m1.end(); it  )
	{
		cout << "键值: " << (*it).first << "  实值: "<<(*it).second << endl;
	}
}
//map容器的构造和赋值
void test()
{
	//1.默认构造函数
	map<int, int> m1;
	//插入元素
	for (int i = 1,j=0; i <=3; i  ,j  )
	{
		   //pair对组不需要包含头文件
			m1.insert(pair<int, int>(i, j));
	}
	if (m1.empty())
	{
		cout << "容器为空" << endl;
	}
	else {
		cout << "容器大小为: " << m1.size() << endl;
	}
    //交换容器
	map<int, int> m2;
	m2.insert(pair<int, int>(1, 520));
	m2.insert(pair<int, int>(2,250));
	m2.insert(pair<int, int>(3, 233));
	cout << "容器交换前: " << endl;
	print(m1);
	cout << "__________________________" << endl;
	print(m2);
	cout << "nn";
	cout << "容器交换后: " << endl;
	m1.swap(m2);
	print(m1);
	cout << "__________________________" << endl;
	print(m2);
}
int main()
{
	test();
	system("pause");
	return 0;
}

0 人点赞