51 lines
1.2 KiB
C++
51 lines
1.2 KiB
C++
|
#include <iostream>
|
||
|
#include <set>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
template <typename T>
|
||
|
void print(const set<T> &s)
|
||
|
{
|
||
|
for (typename set<T>::const_iterator it = s.begin(); it != s.end(); ++it)
|
||
|
cout << *it << ' ';
|
||
|
cout << endl;
|
||
|
}
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
int m[] = {5, 12, 16, 21, 22, 27, 29, 30};
|
||
|
set<int> s(m, m + 8);
|
||
|
print(s); // set 键值自动排序,且不重复
|
||
|
|
||
|
// 查看大于等于 22 值的所有元素
|
||
|
cout << "查看大于等于 22 值的所有元素: " << endl;
|
||
|
set<int>::iterator it = s.lower_bound(22); // 返回第一个大于等于 22 的元素的迭代器
|
||
|
while (it != s.end())
|
||
|
{
|
||
|
cout << *it << ' ';
|
||
|
++it;
|
||
|
}
|
||
|
cout << endl;
|
||
|
|
||
|
// 查找小于等于 22 值的所有元素
|
||
|
cout << "查找小于等于 22 值的所有元素: " << endl;
|
||
|
// it = s.upper_bound(22); // 返回第一个大于 22 的元素的迭代器
|
||
|
// for (; it != s.begin();)
|
||
|
// {
|
||
|
// --it;
|
||
|
// cout << *it << ' ';
|
||
|
// }
|
||
|
// cout << endl;
|
||
|
|
||
|
// 查找小于等于 22 值的所有元素(另一种写法)
|
||
|
it = s.lower_bound(22);
|
||
|
while (it != s.begin())
|
||
|
{
|
||
|
--it;
|
||
|
cout << *it << ' ';
|
||
|
}
|
||
|
cout << endl;
|
||
|
|
||
|
return 0;
|
||
|
}
|