为什么在这个代码结束循环中没有得到结束

why in this code end loop is not get end?

本文关键字:结束 循环 代码 为什么      更新时间:2023-10-16

我正在字符串中弹出矢量中的数据。但打印后代码没有出来为什么?应该做些什么来使它正确。

#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();
}
}

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