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

Segmentation fault: Core dumped C++ vector pairs of string:

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

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

您的问题是您正在对未初始化的向量执行 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,这会读取两个输入,我已经在上面的代码中为你修复了它。