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

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

问题描述:

#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++向量对字符串:

谢谢

你的问题是,你正在做一个未初始化的向量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,我在上面的代码固定它。

+1

感谢他的工作正常! :)同样感谢您提供的关于向量和分段错误的链接。这也非常有帮助! –