如何在c ++中打印给定桶号的所有元素unordered_set?

How to print all the elements of given bucket number in c++ unordered_set?

本文关键字:元素 unordered set 打印      更新时间:2023-10-16

我在 c++ 中有一个unordered_set<string> ht,其中给定的存储桶编号说 x,我必须打印 ht[x] 的给定存储桶中的所有元素,即我正在尝试打印给定存储桶编号 x 中的所有元素。 最后一个 else 块有它:

unordered_multiset<string>ht;
ll m;
cin>>m;
ht.reserve(m);
ll q;
cin>>q;
while (q--){
string cmd;
cin>>cmd;
if(cmd=="add"){
string s;
cin>>s;
if(ht.find(s)==ht.end()){
ht.insert(s);
}
}else if(cmd=="del"){
string s;
cin>>s;
if(ht.find(s)!=ht.end()){
auto it = ht.find(s);
ht.erase(it);
}
}else if(cmd=="find"){
string s;
cin>>s;
if(ht.find(s)!=ht.end()){
cout<<"yes"<<'n';
}else{
cout<<"no"<<'n';
}
}else{
ll x;
cin>>x;
auto it = ht.begin(x);
for(; it!=ht.end(x);it++){
cout<<*it<<' ';
}
cout<<'n';
}

begin(<bucket number>)end(<bucket number>)成员函数可用于迭代特定存储桶中的元素。bucket_count()成员函数返回存储桶数。所以:

#include <unordered_set>
int main() {
std::unordered_set<int> foo;
for(size_t bno = 0; bno < foo.bucket_count(); ++bno) {
for(auto bit = foo.begin(bno), end = foo.end(bno); bit != end; ++bit) {
const auto& element = *bit;
// do stuff with element
}
}
}