提问者:小点点

为什么在这个代码中,end循环不是get end?


我正在尝试弹出向量中的数据。 但是打印后代码不出来是为什么呢? 应该怎么做才能使它正确。

#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个答案

匿名用户

在取消引用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();
        }

}