英文:
Size of unordered map keeps increasing
问题
在最后的for循环中,unordered_map的大小为什么会增加?为什么会这样?
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()){
return false;
}
unordered_map<char, int> sm;
unordered_map<char, int> tm;
for (int i = 0; i < s.size(); i++){
sm展开收缩]++;
tm[t[i]]++;
}
for (int j = 0; j < sm.size(); j++){
cout << j << endl;
cout << sm.size() << endl;
if(sm[j] != tm[j]){
cout << sm[j] << endl;
cout << tm[j] << endl;
cout << j << endl;
return false;
}
}
return true;
}
};
我尝试在网上搜索,但找不到相关的答案。
英文:
The size of unordered map keeps increasing in the last for loop? Why is it so?
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()){
return false;
}
unordered_map<char,int> sm;
unordered_map<char,int> tm;
for (int i = 0; i<s.size();i++){
sm展开收缩]++;
tm[t[i]]++;
}
for (int j = 0; j<sm.size();j++){
cout << j << endl;
cout << sm.size() <<endl;
if(sm[j] != tm[j]){
cout << sm[j] << endl;
cout << tm[j] << endl;
cout << j << endl;
return false;
}
}
return true;
}
};
I have tried to search online but can't find any relevant answer.
答案1
得分: 2
https://en.cppreference.com/w/cpp/container/unordered_map/operator_at
返回映射到等同于键的值的引用,如果这样的键不存在,则执行插入操作。
sm[j] != tm[j]
对于映射,[]
运算符在键不存在时插入条目。
您可能想要调用 .find(j)
代替。
英文:
https://en.cppreference.com/w/cpp/container/unordered_map/operator_at
> Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
sm[j] != tm[j]
The []
operator on maps inserts entries if they didn't already exist.
You probably wanted to call .find(j)
instead
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论