C++: Storing structs in a stack

寵の児 提交于 2019-12-10 13:24:45

问题


I have a struct:

    struct Vehicle
{
    char ad; // Arrival departure char
    string license; // license value
    int arrival; // arrival in military time
};

I want to store all the values in the struct in a stack.

I can store one value in the stack by doing:

    stack<string> stack; // STL Stack object
    Vehicle v; //vehicle struct object
    stack.push(v.license);

How can I store a the whole struct in the stack so I can later access the char, int, and, string?


回答1:


Simple, just replace string for Vehicle and an instance of string for an instance of Vehicle:

stack< Vehicle > stack; // STL Stack object
Vehicle v; //vehicle struct object
stack.push(v);



回答2:


The type between the < and > is what your stack will hold. The first one held strings, you can have one that holds Vehicles:

std::stack<Vehicle> stack;
Vehicle v;
stack.push(v);



回答3:


What would happen when v goes out of scope? I guess you'd better created object on the heap and stores pointers to them in your stack:

void Foo(Stack <Vehicle>& stack) {
  Vehicle* vPtr = new Vehicle();
  stack.push(vPtr);
}



回答4:


How could I push g in stack ?

#include<iostream>
#include<stack>
using namespace std;
struct node{
    int data;
    struct node *link;
};

main(){
    stack<node> s;
    struct node *g;
    g = new node;
    s.push(g); 
}


来源:https://stackoverflow.com/questions/8126955/c-storing-structs-in-a-stack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!