I was curious if there was something akin the the Java hashset in c++. I.e a data structure with fast look, as I will only be running .contains(e) on it. Likewise, if you could enlighten me on how to do a .contains() on whatever data structure you propose, I would be very appreciative. O, please do not post just look at the c++ docs as I have already done so and find them burdensome.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can use std::unordered_set<>
(standard § 23.5.6), its find
method (to do a lookup) as an average complexity of O(1) :
#include <iostream>
#include <unordered_set>
int main()
{
std::unordered_set<int> example = {1, 2, 3, 4};
auto search = example.find(2);
if(search != example.end()) {
std::cout << "Found " << (*search) << '\n';
}
else {
std::cout << "Not found\n";
}
}
EDIT:
As suggested by @Drew Dormann, you can alternatively use count
, which also has a average complexity of O(1):
#include <iostream>
#include <unordered_set>
int main()
{
std::unordered_set<int> example = {1, 2, 3, 4};
if(example.count(2)) {
std::cout << "Found\n";
}
else {
std::cout << "Not found\n";
}
}