【问题标题】:unordered_set count function returns wrong valueunordered_set 计数函数返回错误值
【发布时间】:2020-03-02 10:53:52
【问题描述】:

当有3 a 时,为什么set.count('a') 输出1

程序:

bool isAnagram(string s, string t) {

    unordered_set<char> set;

    for(int i=0; i<s.size(); i++){
        set.insert(s[i]);
    }

    cout << endl << set.count('a') << endl;
    return false;
}

输入:

s = 'anagram'

输出:

1

【问题讨论】:

  • reference 中的第一句:"返回 key 与指定参数 key 比较相等的元素的数量,即 1 或 0,因为此容器不允许重复。”
  • 你应该复习一下集合的数学概念。

标签: c++ unordered-map unordered-set


【解决方案1】:

集合中只有一个a。如果你想要多个as,你需要使用multiset

例子:

#include <iostream>
#include <set>
#include <string>

size_t count_char(const std::string& s, char ch) {
    // fill the set directly using the strings begin and end iterators
    std::multiset<char> set(s.begin(), s.end());

    return set.count(ch);
}

int main() {
    std::cout << count_char("anagram", 'a') << '\n';
}

输出:

3

【讨论】:

    【解决方案2】:

    你必须在计数函数中指定范围:

    count (InputIterator first, InputIterator last, const T& val)
    

    例子:

    #include <iostream>
    #include <algorithm>
    using namespace std;
    
    int main(){
        string s= "anagram";
    
        cout << count(s.begin(), s.end(), 'a') << endl;
        return 0;
    }
    

    输出:

    3
    

    【讨论】:

      猜你喜欢
      • 2021-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2011-03-15
      • 2020-11-22
      • 2019-05-02
      相关资源
      最近更新 更多