簡體   English   中英

分段錯誤:核心轉儲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;

這兩行導致什么是分段錯誤?

向量按需增長,它們不像預先初始化大小並基於索引訪問數組的數組。 請閱讀更多關於載體的信息


解:

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則讀取兩個輸入,我已經在上面的代碼中為你修復了它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM