【问题标题】:Segmentation Fault 11 with Maps and vector c++使用地图和矢量 c++ 的分段错误 11
【发布时间】:2018-06-13 19:48:53
【问题描述】:

我正在尝试从给定文本中获取频率表。 但输出显示分段错误 11。我不知道为什么。 我是新手。您对代码的帮助将不胜感激。 您也可以编辑我的代码,让我学习更好的代码编写方法。非常感谢。

#include<iostream>
#include<map>
#include<string>
#include<vector>

void make_table(vector<pair<char, int> > &table , string path){
    string text = "Hello thusnvkj.ernbuilvgqboipghq3pojavnaj.,fbvlkarebihfg094why091[3tugjvlksbdfv  ajklvrpt-30qjhrgiaoehk.BL;H]IH;LGBJSFDNOWI;HBPWRHGB;ORTWIHGOQHRWI0TUGJRLKEWHUGIH49P0-IT302-UR9GM,NXM,BNX,MNMB/E/RGP'KGP34OR[2=O-O-=0-3-1I0-439890375892R0U;L.GNLS.N.SVMS/FS/FKWEP[IF0W))_*(&*(^^&$%#^%$&%*(^*&)(*)_*_(()())))]]'";
    map<char, int> m;
    for(int i=0; text[i]!='\0'; i++){
        m[text[i]]++;
    }
    map<char,int>::iterator it;
    int j=0;
    for(it=m.begin();it!=m.end(); it++){
        table[j].first=it->first;
        table[j].second=it->second;
        j++;
        //cout << it->first << "   " << it->second << endl;
    }
    return;
}
int main(){
    vector<pair<char , int> > table;
    string path;
    //cin >> path;
    path= "Hi";
    make_table(table, path);
    // make_table function will give us the sorted table(vector of pair) in the decreasing order of frequency of a character.
    /*for(int i =0; i<table.size(); i++){
        cout << table[i].first << "     " << table[i].second << endl;
    }
    */
    return 0;
}

【问题讨论】:

    标签: c++11 dictionary vector segmentation-fault


    【解决方案1】:

    因为您尝试访问空向量中的元素而收到错误

    table[j].first=it->first;
    table[j].second=it->second;
    

    这里可以在for循环外加一行

    table.resize(text.size());
    

    【讨论】:

      猜你喜欢
      • 2018-01-13
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      相关资源
      最近更新 更多