【问题标题】:How to print all the elements of given bucket number in c++ unordered_set?如何在c ++ unordered_set中打印给定桶号的所有元素?
【发布时间】:2020-06-18 14:14:06
【问题描述】:

我在 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(x)end(x) 并编写一个循环
  • @idclev463035818 可以开始做,我对此不太了解,请您进一步解释一下。
  • 我不知道您需要进一步解释什么,这就是为什么最好展示您尝试过的内容并尝试提出更具体的问题。 (顺便说一句,我自己从未使用过它,我只是在这里阅读en.cppreference.com/w/cpp/container/unordered_set,发现看起来相当简单)
  • 请停止ll。没有理由为 long long 引入 typedef,除非你想让你的代码不可读。

标签: c++ hashtable unordered-set


【解决方案1】:

begin(&lt;bucket number&gt;)end(&lt;bucket number&gt;) 成员函数可用于迭代特定存储桶中的元素。 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
        }
    }
}

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多