C++ STL中unordered_set find()函数
在C++的STL中,unordered_set是一个无序的关联容器,它是由一个哈希表实现的。使用unordered_set容器可以快速地进行查找和插入操作,效率非常高。在这篇文章中,我们将讨论unordered_set容器中的find()函数。
什么是unordered_set?
在C++的STL中,unordered_set是一个无序的关联容器,它是由一个哈希表实现的。unordered_set中存储的元素是唯一的,重复的元素将被忽略。unordered_set中的元素是按照它们的哈希值来组织的,因此访问元素的效率非常高。
下面是一个使用unordered_set的示例:
#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<int> mySet = {1, 3, 5, 7, 9};
for (auto it = mySet.begin(); it != mySet.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
输出结果为:
9 3 1 7 5
可以看到,输出结果是无序的。
find()函数的作用
find()函数用于在unordered_set中查找指定的元素。如果查找成功,则返回该元素的迭代器;否则返回unordered_set::end()。
下面是一个使用find()函数的示例:
#include <iostream>
#include <unordered_set>
int main() {
std::unordered_set<int> mySet = {1, 3, 5, 7, 9};
auto it = mySet.find(3);
if (it != mySet.end()) {
std::cout << "Element found in the set" << std::endl;
} else {
std::cout << "Element not found in the set" << std::endl;
}
return 0;
}
输出结果为:
Element found in the set
可以看到,find()函数找到了值为3的元素,返回的迭代器指向该元素。
如果要在unordered_set中查找自定义类型的元素,需要重载该类型的==运算符和hash()函数。下面是一个使用自定义类型的示例:
#include <iostream>
#include <unordered_set>
struct Person {
std::string name;
int age;
bool operator==(const Person& p) const {
return (name == p.name && age == p.age);
}
};
namespace std {
template<> struct hash<Person> {
size_t operator()(const Person& p) const {
return hash<std::string>()(p.name) ^ hash<int>()(p.age);
}
};
}
int main() {
std::unordered_set<Person> mySet = {{"Alice", 20}, {"Bob", 30}, {"Charlie", 40}};
auto it = mySet.find({"Bob", 30});
if (it != mySet.end()) {
std::cout << "Element found in the set" << std::endl;
} else {
std::cout << "Element not found in the set" << std::endl;
}
return 0;
}
输出结果为:
Element found in the set
可以看到,find()函数找到了值为{"Bob", 30}的元素,返回的迭代器指向该元素。
总结
unordered_set容器是一个无序的关联容器,使用哈希表来实现。find()函数用于在unordered_set中查找指定的元素。如果查找成功,则返回该元素的迭代器;否则返回unordered_set::end()。如果要在unordered_set中查找自定义类型的元素,需要重载该类型的==运算符和hash()函数。
极客笔记