【问题标题】:why i am getting segmentation fault error while calling this function?为什么在调用此函数时出现分段错误错误?
【发布时间】:2020-06-15 04:56:18
【问题描述】:

下面的函数接收两个参数,一个是包含字符串的'magazine',另一个是包含注释的'note'。如果 'magazine' 包含所有 'note' 字符串,我们必须打印 Yes 否则 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;
}

【问题讨论】:

  • 请发送minimal reproducible example。例如你怎么调用这个函数?该代码取决于notes 至少与magazine 一样大。
  • 如果笔记大小不同..
  • 因为 n 是杂志的大小,当杂志的大小大于笔记的大小时,它会抛出异常。第二个 for 循环应该检查直到音符的长度。
  • 第一个循环体可能只是 m[magazine[i]]++; ,未知条目默认为 0
  • 知道了,在第二个 for 循环之前应该有 n = note.size();

标签: c++ dictionary vector stl


【解决方案1】:

这是我修正错误后的正确代码:

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;
}

【讨论】:

    【解决方案2】:

    您应该在开始第二个循环之前将 "n" 初始化为 "notes" 的大小。 仍然要获得正确的解决方案,您需要将 "if(m.find(note[i])==m.end()){" 更新为 "if(m.find (note[i])==m.end() || m[note[i]] == 0){"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      • 2019-01-03
      相关资源
      最近更新 更多