unordered_set count 函数返回错误值

new*_*mer 0 c++ unordered-map 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;
}
Run Code Online (Sandbox Code Playgroud)

输入:

s = 'anagram'
Run Code Online (Sandbox Code Playgroud)

输出:

1
Run Code Online (Sandbox Code Playgroud)

Ted*_*gmo 7

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';
}
Run Code Online (Sandbox Code Playgroud)

输出:

3
Run Code Online (Sandbox Code Playgroud)