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?
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);
The type between the <
and >
is what your stack will hold. The first one held string
s, you can have one that holds Vehicles
:
std::stack<Vehicle> stack;
Vehicle v;
stack.push(v);
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);
}
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);
}