C++: Storing structs in a stack

2019-06-20 04:34发布

问题:

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


标签: c++ struct stack