Set 和 multiset 容器(三)

Set 和 multiset 容器(三)

开发工具与关键技术:Visual Studio、C++
作者:张国军
撰写时间:2019年08月17日

set 的查找

#include  <iostream>
#include <set>
using  namespace std;
void show(set<int>setInt)
{
	for (set<int>::iterator it = setInt.begin(); it != setInt.end(); ++it)
	{
		int iItem = *it;
		cout << iItem<<" "; //或直接使用 cout << *it
	}
	cout << endl;
}
void main()
{
	//set.find(elem); //查找 elem 元素,返回指向 elem 元素的迭代器。
	//set.count(elem); //返回容器中值为 elem 的元素个数。对 set 来说,要么是 0,要么是 1。对 multiset 来说,值可能大于 1。
	//set.lower_bound(elem); //返回第一个>=elem 元素的迭代器。
	//set.upper_bound(elem); //返回第一个>elem 元素的迭代器。
	//set.equal_range(elem); //返回容器中与 elem 相等的上下限的两个迭
	//代器。上限是闭区间,下限是开区间,如[beg, end)。
	set<int> setInt;
	setInt.insert(3);
	setInt.insert(1);
	setInt.insert(7);
	setInt.insert(5);
	setInt.insert(9);
	set<int>::iterator itA = setInt.find(5);
	int iA = *itA; //iA == 5
	cout << "setInt.find(5):" << *itA << endl;
	int iCount = setInt.count(5); //iCount == 1
	cout << "setInt.count(5):" << iCount << endl;
	set<int>::iterator itB = setInt.lower_bound(5);
	set<int>::iterator itC = setInt.upper_bound(5);
	int iB = *itB; //iB == 5
	cout << "setInt.lower_bound(5):" << iB << endl;
	int iC = *itC; //iC == 7
	cout << "setInt.upper_bound(5):" << iC << endl;
	pair< set<int>::iterator, set<int>::iterator > pairIt = setInt.equal_range(5);
	cout <<"*pairIt.first:"<< *pairIt.first <<"\t *pairIt.second:"<< *pairIt.second << endl;
}

在这里插入图片描述
//pair 是什么?
pair 的使用

#include  <iostream>
#include <set>
using  namespace std;
void show(set<int>setInt)
{
	for (set<int>::iterator it = setInt.begin(); it != setInt.end(); ++it)
	{
		int iItem = *it;
		cout << iItem<<" "; //或直接使用 cout << *it
	}
	cout << endl;
}
void main()
{
	set<int> setInt;
	setInt.insert(3);
	setInt.insert(1);
	setInt.insert(7);
	setInt.insert(5);
	setInt.insert(9);
	//pair 译为对组,可以将两个值视为一个单元。
	//pair<T1, T2>存放的两个值的类型,可以不一样,如 T1 为 int,T2 为 float。
	//T1, T2 也可以是自定义类型。
	//pair.first 是 pair 里面的第一个值,是 T1 类型。
	//pair.second 是 pair 里面的第二个值,是 T2 类型。
	//往 setInt 容器插入元素 1,3,5,7,9
	pair< set<int>::iterator, set<int>::iterator > pairIt = setInt.equal_range(5);
	set<int>::iterator itBeg = pairIt.first;
	set<int>::iterator itEnd = pairIt.second;
	cout << *itBeg <<"\t"<< *itEnd << endl;
	//此时 *itBeg==5 而 *itEnd == 7s
}

在这里插入图片描述
小结:
一、容器 set/multiset 的使用方法;  红黑树的变体,查找效率高,插入不能指定位置,插入时自动排序。 
二、functor 的使用方法;  类似于函数的功能,可用来自定义一些规则,如元素比较规则。 
三、pair 的使用方法。  对组,一个整体的单元,存放两个类型(T1,T2,T1 可与 T2 一样)的两 个元素。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值