Associating stack with struct in C++

Asked

Viewed 156 times

1

Construct the following program:

#include <iostream>
#include <stack>

using namespace std;

struct Register{

    string name;
    int birth;
    char sex;

    void Insert(string st_name,int st_birth, char st_sex){

        name=st_name;
        birth=st_birth;
        sex=st_sex;
    }

};

stack <Register> stack_register;

int main(void){

    Register data[5];

    data[0].Insert("Pkrtvx",151,'M');
    stack_register.push(data[0]);

    data[1].Insert("IKXS_36080",159,'M');
    stack_register.push(data[1]);

    return 0;
}

My doubts:

  1. Did I enter the data from struct in my stack in the right way?

  2. How do I show the top element in this case? Because every time I use the top finished one returns an error.

See the code below to understand:

#include <iostream>
#include <stack>

using namespace std;

struct Register{

    string name;
    int birth;
    char sex;

    void Insert(string st_name,int st_birth, char st_sex){

        name=st_name;
        birth=st_birth;
        sex=st_sex;
    }

};

stack <Register> stack_register;

int main(void){

    Register data[5];

    data[0].Insert("IKXS_36080",125,'M');
    stack_register.push(data[0]);

    data[1].Insert("IKXS_36080",105,'M');
    stack_register.push(data[1]);

    cout << stack_register.top(); //O erro estar aqui

    return 0;
}
  • Can [Edit] the question and add the error message?

1 answer

3


The mistake that gives is:

no match for 'Operator<<' in 'Std::Cout << stack_register.Std::stack<_Tp, _Sequence>::top

That says the handwriting operator << does not know how to write a structure Register on the console.

Has two solutions.

  1. Write structure fields manually:

    cout << "Nome: " << stack_register.top().name;
    

    Note that you have the .name at the end to write the name

  2. Build a custom writing function

    This is done by implementing the write operator <<, thus:

    std::ostream& operator << (std::ostream &o,const Register &a){
        //Aqui consideramos que escrever um register na consola escreve o nome e o sexo
        return o<<"Nome: "<<a.name<<"\nSexo: "<<a.sex; 
    }
    

    Which already allows you to do what you were initially

    cout<<stack_register.top();
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.