stack implementation in c++ with struct
Apr 7, 2014 at 9:12am UTC
Hi,
I am trying to implement a stack class which has struct data type as its private member. I am getiing the following error ,
bash-3.2$ g++ stack_str_arr.cpp
stack_str_arr.cpp: In member function ‘void stack::push(int)’:
stack_str_arr.cpp:39: error: ‘top’ was not declared in this scope
stack_str_arr.cpp: At global scope:
stack_str_arr.cpp:43: error: no ‘void stack::display()’ member function declared in class ‘stack’
I am a beginner, please let me know what mistake am making here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#include<iostream>
using namespace std;
#define MAX 5
class stack
{
public :
stack();
void push(int );
int pop();
private :
//struct st s ;
struct st {
int top;
int arr[MAX];
} s;
};
stack::stack()
{
s.top = -1;
}
void ::stack::push(int elem)
{
if (s.top == MAX-1)
{
cout<<"\nStack is full" <<endl;
}
else
{
s.top++;
s.arr[top] = elem;
}
}
void ::stack::display()
{
for (int i=0; i<= MAX;i++)
{
cout<<s.arr[i]<<endl;
}
}
int main()
{
stack stobj;
stobj.push(5);
stobj.push(51);
stobj.push(52);
stobj.push(54);
stobj.push(53);
stobj.display();
}
Apr 7, 2014 at 9:25am UTC
1 2 3 4 5 6 7 8 9 10 11 12
void stack::push(int elem)
{
if (s.top == MAX-1)
{
cout<<"\nStack is full" <<endl;
}
else
{
s.top++;
s.arr[s. top] = elem;
}
}
EDIT: And change all those
void ::stack::
to
void stack::
.
Last edited on Apr 7, 2014 at 3:46pm UTC
Apr 8, 2014 at 3:39am UTC
@4 MAX is system (from limits header) macro. So replace it with ARR_MAX or something that sort of.
@35 top is a data member within struct st object s. So it has to be accessed through s, like: s.arr[s.top] = elem;
@main function. It has non-void return type (int). Include a return statment in the end.
Replace all void::stack::* with void stack::*
@For loop in display function. The arrange range should be 0 to ARR_MAX-1 i.e i=0; i<ARR_MAX.
All the above are fixed in the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
#include <iostream>
#define ARR_MAX 5
class stack
{
public :
stack();
void push(int );
void display(void );
int pop();
private :
struct st {
int top;
int arr[ARR_MAX];
} s;
};
stack::stack()
{
s.top = -1;
}
void ::stack::push(int elem)
{
if (s.top == ARR_MAX-1)
{
std::cout << "\nStack is full" << std::endl;
}
else
{
s.top++;
s.arr[s.top] = elem;
}
}
void ::stack::display()
{
for (int i=0; i< ARR_MAX;i++)
{
std::cout << s.arr[i] << std::endl;
}
}
int main()
{
stack stobj;
stobj.push(1);
stobj.push(2);
stobj.push(3);
stobj.push(4);
stobj.push(5);
stobj.display();
return 0;
}
Topic archived. No new replies allowed.