【问题标题】:Segmentation fault: Core dumped C++ vector pairs of string:分段错误:核心转储 C++ 向量对字符串:
【发布时间】:2017-06-24 00:02:48
【问题描述】:
#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++ vector segmentation-fault std-pair


    【解决方案1】:

    您的问题是您正在对未初始化的向量执行 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&lt;=n;i++) 如果输入 1,这会读取两个输入,我已经在上面的代码中为您修复了它。

    【讨论】:

    • 谢谢伙计,它工作正常! :) 还要感谢您提供的有关向量和分段错误的链接。这也很有帮助!
    猜你喜欢
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2017-02-25
    • 2016-07-12
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多