在 C++ 语言的 STL 标准模板库 , std::set 集合容器 是一个存储唯一元素的容器 , 该容器的底层使用 红黑树 数据结构 实现 ; std::set 容器是有序的 , 存储元素时 会自动按指定规则进行排序 ;
std::set 集合容器类 提供了一个 find 成员函数 , 用于查找 集合容器中 指定值的元素 ;
std::set#find() 函数原型 如下 :
iterator find(const key_type& k) const;
在下面的代码示例中 ,
首先 , 创建了一个包含整数 1 到 5 的 std::set 集合容器 ,
// 初始化
set<int> mySet = { 1, 2, 3, 4, 5 };
然后 , 使用 find 函数查找整数 3 ;
// 调用
auto it = mySet.find(3);
最后 , 如果找到 整数 3 , 迭代器指向找到的元素 , 如果没有找到元素 , 迭代器指向末尾位置 ; 可以根据判断 返回的 迭代器是否等于 mySet.end() 值确定 ,
// 如果找到元素, 迭代器指向找到的元素
// 如果没有找到元素 , 迭代器指向末尾位置
if (it != mySet.end()) {
cout << "找到元素 : " << *it << endl;
}
else {
cout << "未找到元素 "<< endl;
}
代码示例 :
#include "iostream"
using namespace std;
#include "set"
int main() {
// 初始化
set<int> mySet = { 1, 2, 3, 4, 5 };
// 调用
auto it = mySet.find(3);
// 如果找到元素, 迭代器指向找到的元素
// 如果没有找到元素 , 迭代器指向末尾位置
if (it != mySet.end()) {
cout << "找到元素 : " << *it << endl;
}
else {
cout << "未找到元素 "<< endl;
}
// 控制台暂停 , 按任意键继续向后执行
system("pause");
return 0;
};
执行结果 :
找到元素 : 3 请按任意键继续. . .
std::set 集合容器 中的每个元素都是唯一的 , 对于任何元素 , 它 在集合中要么存在 , 要么不存在 , 这意味着其计数只能是 0 或 1 ;
在 std::multiset 集合容器 中 , 统计元素个数是有意义的 ;
std::set 集合容器类 提供了一个 count 成员函数 , 用于确定集合中特定元素的数量 ;
这是为了保持与其他 关联容器的接口一致性 , 如 : std::multiset 容器 , std::set 也提供了这个函数接口 ;
count 函数原型如下 :
size_type count(const key_type& k) const;
在下面的代码中 , 使用 count 函数来检查整数元素 3 是否存在于集合中 , 由于 std::set 集合容器可以保证元素的唯一性 ,
代码示例 :
#include "iostream"
using namespace std;
#include "set"
int main() {
// 初始化
set<int> mySet = { 1, 2, 3, 4, 5 };
// 获取元素 3 的个数
auto count = mySet.count(3);
// 获取元素 6 的个数
auto count2 = mySet.count(6);
cout << "元素3 : " << count << endl;
cout << "元素6 : " << count2 << endl;
// 控制台暂停 , 按任意键继续向后执行
system("pause");
return 0;
};
执行结果 :
元素3 : 1 元素6 : 0 请按任意键继续. . .