Sep 11, 2013 at 11:29am UTC
The element of the type your stack was designed for. set_values() is kind of meaningless in this context. Your class lacks dtor, copy ctor and assignment operator.
Sep 11, 2013 at 11:39am UTC
Ok, I edited the code. But whats wrong now?
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
#include <iostream>
using namespace std;
class stack{
private :
int *st;
int s;
int top;
public :
stack(int );
//void set_values();
//void get_values();
void push(int );
};
stack::stack(int x)
{
s=x;
top=0;
st=new int [s];
}
/*
void stack::set_values()
{
for(int i=0; i<s; ++i)
st[i]=rand()%10;
}
void stack::get_values()
{
for(int i=0; i<s; ++i)
cout<<st[i]<<endl;
}
*/
void stack::push(int x)
{
st[++top]=x;
}
int main()
{
stack sc(10);
//sc.set_values();
//sc.get_values();
for (int i=0; i<s; ++i){
st[i]==rand()%10;
sc.push(st[i]);
}
system ("Pause" );
return 0;
}
Last edited on Sep 11, 2013 at 11:39am UTC
Sep 11, 2013 at 11:44am UTC
1 2 3 4 5 6 7
void Stack::push( int x )
{
if ( top < s )
st[top++] = x;
else
std::cerr << "Stack overflow!\n" ;
}
Last edited on Sep 11, 2013 at 11:46am UTC
Sep 11, 2013 at 11:45am UTC
Variables *st and s are invalid in main(). Is it because I initialized them in "private:"?
Sep 11, 2013 at 11:49am UTC
Dude, the problem for me is in main(); not in push()
I need to pass random values in push().
Sep 11, 2013 at 11:59am UTC
1 2 3 4 5
void stack::set_values()
{
for (int i=0; i<s; ++i)
st[i]=rand()%10;
}
In this function, s and st are valid because of initialization in
private: .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main()
{
stack sc(10);
//sc.set_values();
//sc.get_values();
for (int i=0; i<s; ++i){
st[i]==rand()%10;
sc.push(st[i]);
}
system ("Pause" );
return 0;
}
But here, s and st are invalid although I've initialized in
private: . Why?
Last edited on Sep 11, 2013 at 11:59am UTC
Sep 11, 2013 at 12:05pm UTC
You answered you own question. You've declared them private , so they won't be available with direct access outside of the class. For example, in order to retrieve the value of s, you'll need an accessor method for s. Just overload operator[], #include <ctime> and <cstdlib>, generate and assign the numbers to sc.
Last edited on Sep 11, 2013 at 12:19pm UTC
Sep 11, 2013 at 12:10pm UTC
But here, s and st are invalid although I've initialized in private:. Why?
That has nothing to do with private.
s
and
st
are members of
stack
and can only accessed via
sc
.
[EDIT]
to fill your stack with value do it like so:
1 2 3
for (int i=0; i<10; ++i){
sc.push(rand()%10);
}
[Normally you should call srand() before rand()]
Last edited on Sep 11, 2013 at 12:13pm UTC
Sep 11, 2013 at 12:21pm UTC
Look at coder777's post. What i described is not neccessary.
P.S. But you still need the destructor, operator= and copy ctor.
Sep 11, 2013 at 12:53pm UTC
Thanx a lot coder. Part of the code has been solved.