c++ - 为什么在这个代码结束循环中没有结束?
问题描述
我正在尝试弹出向量中的数据。但是打印后代码不出来为什么?应该怎么做才能使它正确。
#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();
}
}
推荐阅读
- javascript - JS 脚本在刷新后在局部视图中不起作用
- php - Swift_TransportException 无法与主机建立连接:stream_socket_client
- tcl - 更新 tcl 脚本的 $auto_path,在其中包含一个变量
- javascript - 在nodejs的打字稿类中使用路由器对象时出现异常
- mysql - 我想在一个选择查询中获得 3 列或更多列
- angular - 当具有多个 AsyncValidator 时,Angular FormBuilder 处于待处理状态
- rspec - Rspec Hash Matcher 与键顺序无关
- dynamic - 如何在其中实现动态等待?
- c# - 如何从函数中返回值
- java - 为 JAX-RS 创建 JdkHttpServer 时出现 AbstractMethodError