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

问题描述 投票:1回答:1
#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;
}

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

c++ vector segmentation-fault std-pair
1个回答
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则读取两个输入,我已经在上面的代码中为您修复了它。

© www.soinside.com 2019 - 2024. All rights reserved.