почему в этом коде конец l oop не заканчивается? - PullRequest
0 голосов
/ 13 июля 2020

Я пытаюсь вставить данные в вектор. Но после печати код не выходит Почему? Что нужно сделать, чтобы исправить.

#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 Ответ

4 голосов
/ 13 июля 2020

Вы должны выделить объект, на который будет указывать 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();
        }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...