为什么在此代码中end循环没有结束?

时间:2020-07-13 12:45:00

标签: c++ stl

我想弹出向量中的数据。但是打印后代码没出来 为什么?应该做些什么来使其正确。

#include <iostream>
#include <vector>
using namespace std;

typedef struct add
{
        string name;
        string address;
}Address;
typedef struct st
{
        vector<Address>madder;
}SLL;

int main()
{
        SLL * st;
        int n=3;
        Address ad,rad;
        while(n--)
        {
                cout << "enter the name : ";
                cin >> ad.name;
                cout << "enter the adderess : ";
                cin >> ad.address;
                st->madder.push_back(ad);
        }
        while (!st->madder.empty())
        {
                rad = st->madder.back();
                cout << rad.name << " " <<rad.address <<endl;
                st->madder.pop_back();
        }

}

1 个答案:

答案 0 :(得分:4)

在取消引用st之前,必须分配st指向的对象。

还应该删除分配的内容。

int main()
{
        SLL * st;
        int n=3;
        Address ad,rad;
        st = new SLL; // add this
        while(n--)
        {
                cout << "enter the name : ";
                cin >> ad.name;
                cout << "enter the adderess : ";
                cin >> ad.address;
                st->madder.push_back(ad);
        }
        while (!st->madder.empty())
        {
                rad = st->madder.back();
                cout << rad.name << " " <<rad.address <<endl;
                st->madder.pop_back();
        }
        delete st; // add this

}

另一种选择是不使用指针,而直接将SLL对象分配为变量。

int main()
{
        SLL st;
        int n=3;
        Address ad,rad;
        while(n--)
        {
                cout << "enter the name : ";
                cin >> ad.name;
                cout << "enter the adderess : ";
                cin >> ad.address;
                st.madder.push_back(ad);
        }
        while (!st.madder.empty())
        {
                rad = st.madder.back();
                cout << rad.name << " " <<rad.address <<endl;
                st.madder.pop_back();
        }

}