分段错误:核心转储C ++向量字符串对:

时间:2017-06-24 00:02:49

标签: c++ vector segmentation-fault std-pair

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


using namespace std;

class student{
public:
std::vector <pair<string,string> > stud_details; 
int n;
std::vector <pair<string,string> > get_details(int n);
};

std::vector <pair<string,string> > student::get_details(int n)
{
//std::vector <pair<string,string> > stud_details1;
typedef vector <pair<string,string> > Planes;
Planes stud_details1;
pair<string,string> a;


for(int i=0;i<=n;i++)
    {
    cout<<"Enter the details of the student"<<endl;
    cout<<"Name, subject";
    cin>>stud_details1[i].first;
    cin>>stud_details1[i].second;
    a=make_pair(stud_details1[i].first,stud_details1[i].second);
    stud_details1.push_back(a);
    }
return stud_details1;
}

int main()
{

    student s;
    int n;
    cout<<"Enter the number of people enrolled:";
    cin>>n;
    s.get_details(n);
    return 0;
}

我随机测试了一些东西,但是当我尝试运行上面的代码时,我遇到了分段错误。我该怎么做才能对矢量对问题进行排序?如果是问题的解决方案,我该如何进行动态内存分配?或者我采取的方法是错的?

1 个答案:

答案 0 :(得分:0)

你的问题是你正在对未初始化的矢量做一个cin。

cin>>stud_details1[i].first;
cin>>stud_details1[i].second;

这两行导致What is a segmentation fault?

矢量按需增长,它们不像您预先初始化大小并根据索引访问数组的数组。请详细了解vectors

解决方案:

string name,subject;
cin >> name;
cin >> subject;
stud_details1.push_back(std::make_pair(name,subject));

只需将名称和主题作为两个字符串变量读取,然后与两者进行配对,最后将该对推送到矢量。

完整代码:

#include <iostream>
#include<vector>
#include<string>
#include <algorithm>


using namespace std;

class student{
public:
std::vector <pair<string,string> > stud_details; 
int n;
std::vector <pair<string,string> > get_details(int n);
};

std::vector <pair<string,string> > student::get_details(int n)
{
//std::vector <pair<string,string> > stud_details1;
typedef vector <pair<string,string> > Planes;
Planes stud_details1;
pair<string,string> a;


for(int i=0;i<n;i++)
    {
    cout<<"Enter the details of the student"<<endl;
    cout<<"Name, subject";
    string name,subject;
    cin >> name;
    cin >> subject;
    stud_details1.push_back(std::make_pair(name,subject));
    }
return stud_details1;
}

int main()
{

    student s;
    int n;
    cout<<"Enter the number of people enrolled:";
    cin>>n;
    s.get_details(n);
    return 0;
}

注意:您还有一个逻辑缺陷,for(int i=0;i<=n;i++)如果输入1则会读取两个输入,我已在上面的代码中为您修复了它。