[英]why i am getting segmentation fault error while calling this function?
下面 function 收到两个 arguments 一个是包含字符串的“杂志”,另一个是包含注释的“注释”。 如果 'magazine' 包含所有 'note' 字符串,我们必须打印Yes else No 。
void checkMagazine(vector<string> magazine, vector<string> note) {
map<string, int> m;
int n = magazine.size();
for(int i=0; i<n ; i++){
if(m.find(magazine[i]) == m.end())
m[magazine[i]] = 1;
else
m[magazine[i]]++;
}
for(int i=0; i<n; i++){
if(m.find(note[i])==m.end()){
cout<<"No"<<endl;
return;
}
else{
m[note[i]]--;
}
}
cout<<"Yes"<<endl;
}
这是我改进错误后的正确代码:
void checkMagazine(vector<string> magazine, vector<string> note) {
map<string, int> m;
int n = magazine.size();
for(int i=0; i<n ; i++){
if(m.find(magazine[i]) == m.end())
m[magazine[i]] = 1;
else
m[magazine[i]]++;
}
n = note.size();
for(int i=0; i<n; i++){
if(m.find(note[i]) == m.end() || m[note[i]] == 0){
cout<<"No"<<endl;
return;
}
else{
m[note[i]]--;
}
}
cout<<"Yes"<<endl;
}
您应该在开始第二个循环之前将“n”初始化为“notes”的大小。 仍然要获得正确的解决方案,您需要将"if(m.find(note[i])==m.end()){"更新为"if(m.find(note[i])==m. end() || m[note[i]] == 0){"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.