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?
Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.
Struct members are stored in the order they are declared. (This is required by the C99 standard, as mentioned here earlier.) If necessary, padding is added before each struct member, to ensure correct alignment. Each primitive type T requires an alignment of sizeof(T) bytes.
If the object is of struct type then it may be stored on stack (as a local variable) or on the heap (as a field of another object).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With