map/set增删查改

本文详细介绍了C++标准模板库STL中set和map的使用方法,包括元素的增删查改、自动排序与去重特性。通过具体代码示例展示了如何使用set进行元素操作,以及map在计数等场景的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

set基本使用

增删查改

set<int> s;
	s.insert(1);
	s.insert(3);
	s.insert(2);
	s.insert(1);
	s.insert(4);
	set<int>::iterator it = s.begin();
	while (it != s.end())
	{
		cout << *it << " ";
		++it;
	}
	cout << endl;
	set<int> c = s;
	auto pos = c.find(3);
	c.erase(pos);
	for (auto e : c)
	{
		cout << e << " ";
	}

set会自动排序去重,因为底层是搜索树,中序遍历是有序的

map的基本使用

void test_map()
{
	map<int, int> m;
	m.insert(pair<int, int>(1, 1));
	m.insert(pair<int, int>(1, 1));
	m.insert(make_pair(2, 2));
	m.insert(make_pair(3, 3));
	map<int, int>::iterator it = m.begin();
	while (it != m.end())
	{
		cout << it->first << " " << it->second;
		cout << endl;
		++it;
	}
	cout << endl;
	for (auto e : m)
	{
		cout << e.first << " " << e.second;
		cout << endl;
	}

}

////计数
void test_map3()
{
	map<string, int> m;
	string str[] = { "西瓜", "西瓜", "西瓜", "香蕉", "草莓", "草莓", "西瓜", "西瓜", "西瓜", "西瓜", };
	//map<string, int> m;
	/*for (auto e : str)
	{
		//map<string, int> m;
		map<string, int>::iterator  it = m.find(e);
		if (it != m.end())
		{
			it->second++;
		}
		else
		{
			m.insert(make_pair(e, 1));
		}
	}*/
	for (auto e : str)
	{
		m[e]++;
	}
	for (auto e : m)
	{
		cout << e.first << " " << e.second << endl;
	}
}

//

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值