2017-06-24 102 views
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++向量對字符串:

謝謝

回答

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,我在上面的代碼固定它。

+1

感謝他的工作正常! :)同樣感謝您提供的關於向量和分段錯誤的鏈接。這也非常有幫助! –