c++ - unordered_set 计数函数返回错误值
问题描述
为什么有a时set.count('a')
输出?1
3
程序:
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
解决方案
套装里只有一个a
。如果你想要多个a
s 你需要使用一个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
推荐阅读
- javascript - React - 重用表单组件并根据按钮单击在评论下显示它
- python - python - 如果条件值,预处理器函数打印错误
- ios - 如何在 ImageView 的不同角落对齐 textLabel
- r - 使用 r4.0.2 在 macOS Catalina 版本 10.15.6 上的 RStudio 中安装 leidenbase 和 monocle3 包时出错
- powershell - Powershell ISE $profile 为空
- reactjs - 我在创建一个反应项目时遇到了困难,我不知道我做错了什么
- apache-spark - Mesos 失败并出现错误:无法加载类...命令退出,状态为 101 Spark3、Mesos 1.9.0、Jdk 无头 11 RHEL 7
- html - Div 样式浮动:左侧清除不工作
- javascript - 为什么 getElementsByClassName 和 querySelector 不起作用?
- asp.net-core - 如何在每个 IdentityServer4 api 调用中获取客户端信息?(用于记录目的)