2017-06-24 3 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; 

この2行はWhat is a segmentation fault?

ベクターは、必要に応じて成長し、彼らはあなたのサイズを事前に初期化する配列を好きとインデックスに基づいて配列にアクセスしていない原因となりました。 vectorsについて詳しくは、こちらをご覧ください。


ソリューション:

string name,subject; 
cin >> name; 
cin >> subject; 
stud_details1.push_back(std::make_pair(name,subject)); 

は、ちょうどその両方と対をなす2つの文字列変数として名や件名を読んで、そして最終的にベクトルにそのペアを押してください。


全コード:

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

注:あなたは1が、私は上記のコードではあなたのためにそれを修正し、入力された場合、これは2つの入力を読み込み、またfor(int i=0;i<=n;i++)をロジックの欠陥を持っていました。

+1

ありがとうございました。 :)ベクトルとセグメンテーションの欠陥についてあなたが提供したリンクにも感謝します。とても役に立ちました! –

関連する問題