首页 > 解决方案 > unordered_set 计数函数返回错误值

问题描述

为什么有a时set.count('a')输出?13

程序:

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

标签: c++unordered-mapunordered-set

解决方案


套装里只有一个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

推荐阅读