C++中map类的使用

代码:

附上map类标准库资料:https://en.wikipedia.org/wiki/Associative_containers

#include  
#include  
#include  

using namespace std;
/*map中的数据是默认按照key值自动排序的,如果需要修改排序规则,可以运算符重载<*/
struct person
{
	string name;
	int age;

	person(string name, int age)
	{
		this->name = name;
		this->age = age;
	}

	bool operator < (const person& p) const//运算符左侧对象为调用对象,右侧对象为传参对象
	{
		return this->name < p.name;
	}
};

map m;
int main()
{
	person p1("Tom1", 20);
	person p2("Tom2", 22);
	person p3("Tom3", 22);
	person p4("Tom4", 23);
	person p5("Tom5", 24);
	m.insert(make_pair(p3, 100));
	m.insert(make_pair(p4, 100));
	m.insert(make_pair(p5, 100));
	m.insert(make_pair(p1, 100));
	m.insert(make_pair(p2, 100));

	cout << "地图中的原始数据:" << endl;
	for (map::iterator iter = m.begin(); iter != m.end(); iter++)
	{
		cout << iter->first.name << "\t" << iter->first.age << "\t" << iter->second << endl;
	}
	cout << m.size() << "\t" << m.max_size() << endl;

	cout << "erase操作后的地图数据:" << endl;
	map::iterator iter = m.end();//就像数组begin取得是0,end取的是n,超过索引值

	m.erase(--iter);

	for (map::iterator iter = m.begin(); iter != m.end(); iter++)
	{
		cout << iter->first.name << "\t" << iter->first.age << "\t" << iter->second << endl;
	}
	cout << m.size() << "\t" << m.max_size() << endl;
	cout << "clear操作后的地图数据:" << endl;
	m.clear();//清除地图

	for (map::iterator iter = m.begin(); iter != m.end(); iter++)
	{
		cout << iter->first.name << "\t" << iter->first.age << "\t" << iter->second << endl;
	}
	cout << m.size() << "\t" << m.max_size() << endl;

	system("pause");
	return 0;
}

运行结果:

C++中map类的使用_第1张图片

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