#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;
这两条线导致什么是分割故障?
向量按需生长,它们不像是数组,您可以在索引前进行初始化的大小和访问数组。请阅读有关向量的更多信息。
解决方案:
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,我在上面的代码中为您修复了它。