Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Storing structs in a stack

Tags:

c++

stack

struct

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?

like image 591
Nick Avatar asked Nov 14 '11 19:11

Nick


People also ask

Are structs stored on the stack C?

Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.

Where are structs stored in memory in C?

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.

Are structs stored in heap C?

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).


2 Answers

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);
like image 116
K-ballo Avatar answered Oct 03 '22 16:10

K-ballo


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);
like image 43
Flexo Avatar answered Oct 03 '22 15:10

Flexo