C++map的初始化

map的初始化有两种方式:

1、直接赋值

       map[key]=value;

2、用insert添加pair类型的元素

#include
#include
#include

using namespace::std;

int main()
{
	//直接赋值法
	map m1;
	m1[string("abc")] = 1;
	m1[string("defg")] = 2;

	//用insert添加
	map m2;
	m2.insert({ string("abc"), 1 });
	m2.insert(make_pair(string("defg"), 2));
	m2.insert(pair(string("hijk"), 3));

	//打印 m1,m2
	auto it1 = m1.begin();
	cout << "m1:" << endl;
	while (it1 != m1.end())
	{
		cout << it1->first << " " << it1->second << endl;
		it1++;
	}
	cout <<"m2:" << endl;
	auto it2 = m2.begin();
	while (it2 != m2.end())
	{
		cout << it2->first << " " << it2->second << endl;
		it2++;
	}
	system("pause");
	return 0;
}


你可能感兴趣的:(C++)