2011-11-14 15 views
5

ho una struct:C++: Memorizzazione le strutture in una pila

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

voglio per memorizzare tutti i valori nella struct in una pila.

posso archiviare un valore nello stack facendo:

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

Come posso memorizzare un tutto struct nella pila in modo da poter successivamente accedere al char, int, e, stringa?

risposta

10

Semplice, basta sostituire string per Vehicle e un'istanza di string per un'istanza di Vehicle:

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

Haha, non posso credere che fosse così semplice. Grazie! – Nick

6

Il tipo tra il < e > è ciò che il vostro stack terrà. Il primo tenutosi string s, si può avere uno che tiene Vehicles:

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

cosa sarebbe successo quando v va fuori del campo di applicazione? Immagino sia meglio creare l'oggetto nell'heap e archiviare i puntatori nel proprio stack:

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

posso semplicemente fare stack.push ({new Vehicle()})? –

+0

Mi piace la sintassi poiché specifica che non si intende utilizzare puntatori espliciti su un oggetto appena creato. – Vlad

0

Come posso inserire g nello 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); 
} 
Problemi correlati