在 C++ 中使用 STL Set Container
本文将演示有关如何在 C++ 中使用 STL set
容器的多种方法。
使用 std::set
在 C++ 中声明设置容器对象
std::set
命令将一组排序的唯一对象实现为关联容器。默认情况下,元素使用 std::less
比较函数排序,但用户可以提供自定义函数作为第二个模板参数。相同的标头还提供了 std::multiset
容器,它可以存储多个值而不过滤重复项。
请注意,我们在以下示例中使用初始化列表构造函数创建了两个集合对象。我们还利用了 count
成员函数,它检索具有给定键的集合中存在的元素数量。这个函数对于 std::multiset
容器来说更内在,但是当从 std::multiset
对象调用时,你可以检查元素是否存在相同的函数。
#include <iostream>#include <set>using std::cout; using std::endl;
using std::multiset; using std::set;
template<typename T>
void printSet(set<T> s) {
for (const auto &item : s) {
cout << item << "; ";
}
cout << endl;
}
template<typename T>
void printMultiSet(multiset<T> s) {
for (const auto &item : s) {
cout << item << "; ";
}
cout << endl;
}
#define STR(num) #num
int main()
{
std::set<int> s1 = { 1, 1, 1, 2, 2, 3 };
printSet(s1);
std::multiset<int> s2 = { 1, 1, 1, 2, 2, 3 };
printMultiSet(s2);
std::cout << STR(s2) << " contains " << s2.count(1) << "ones" << endl;
std::cout << STR(s2) << " contains " << s2.count(2) << "twos" << endl;
return EXIT_SUCCESS;
}
输出:
1; 2; 3;
1; 1; 1; 2; 2; 3;
s2 contains 3 ones
s2 contains 2 twos
在 C++ 中使用 insert
成员函数将元素插入到集合中
insert
函数有多个重载,但我们使用带有单个参数的版本,表示要添加到集合中的元素。insert
的重载返回迭代器的 std::pair
对象和 bool
。
后者表示插入是否成功,如果成功,它有一个 true
值。另一方面,当操作成功时,迭代器指向插入的元素。如果失败,则指向阻止插入的元素。请注意,插入操作在容器的大小上具有对数复杂度。
#include <iostream>#include <set>#include <cassert>using std::cout; using std::endl;
using std::multiset; using std::set;
int main()
{
std::set<int> s1 = { 1, 1, 1, 2, 2, 3 };
auto ret = s1.insert(5);
assert(*ret.first == 5);
if (ret.second)
std::cout << "Inserted!" << endl;
ret = s1.insert(1);
assert(*ret.first == 1);
if (!ret.second)
std::cout << "Not inserted!" << endl;
return EXIT_SUCCESS;
}
输出:
Inserted!
Not inserted!
使用 find
成员函数在 C++ 中检索具有给定键的元素的迭代器
find
函数是 std::set
容器的另一个有用的成员函数,它可以将迭代器返回到具有给定键的元素。如果集合中没有这样的元素,则返回尾后迭代器;这有助于用户验证成功的函数调用。
#include <iostream>#include <set>using std::cout; using std::endl;
using std::multiset; using std::set;
int main()
{
std::set<int> s1 = { 1, 1, 1, 2, 2, 3 };
auto search = s1.find(2);
if (search != s1.end()) {
cout << "Found " << (*search) << endl;
} else {
cout << "Not found" << endl;
}
return EXIT_SUCCESS;
}
输出:
Found 2
在 C++ 中使用 contains
成员函数检查具有给定键的元素是否存在于集合中
由于 C++20 语言标准,std::set
提供了成员函数 contains
,这是检查具有给定键的元素是否存在于 set 对象中的更简单的接口。该函数返回布尔值以指示集合中是否存在此类元素。这个函数的运行时间复杂度也是容器大小的对数。
#include <iostream>#include <set>using std::cout; using std::endl;
using std::multiset; using std::set;
int main()
{
std::set<int> s3 = { 91, 123, 63, 122, 22, 53 };
for (int x: {22, 23, 53, 54}) {
if (s3.contains(x)) {
cout << x << ": Found\n";
} else {
cout << x << ": Not found\n";
}
}
return EXIT_SUCCESS;
}
输出:
22: Found
23: Not found
53: Found
54: Not found
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。