Reputation: 61
I am trying to create my own class (NodeWithMin) as elements for stack in C++, and create a new class (StackWithMin) inheriting it. I think i am ok creating the new stack class, but having some problem initialize a new instance of the new class and use it. Does anybody have a good idea with it? I wrote all classes and main in a single file. Thanks.
#include <stack>
class NodeWithMin{
public:
int value;
int min;
NodeWithMin(int v, int min){
this->value = v;
this->min = min;
}
};
template<class NodeWithMin>
class StackWithMin : stack<NodeWithMin>{
public:
typedef stack<NodeWithMin> super;
void push(int value){
int newMin = min(value, this->min());
super::push(new NodeWithMin(value, newMin));
};
int min(){
if(this->isEmpty()){
return numeric_limits<int>::max();
}else{
super::peek().min;
}
};
};
int main(int argc, const char * argv[])
{
StackWithMin<class NodeWithMin>* ss;
ss = new StackWithMin<class NodeWithMin>();
}
Upvotes: 5
Views: 135
Reputation:
First off, I removed
using namespace std;
So I can qualify std
to remove ambiguities.
The first problem I noticed is this line:
int newMin = min(value, this->min());
My guess is you're trying to use min
from algorithm
(since stack
does not contain a min
function):
#include <algorithm>
// snip
int newMin = std::min(value, this->min())
The second problem is you have no instance of stack<NodeWithMin>
, only a typedef. Therefore you need to use it like this:
typedef std::stack<NodeWithMin> super;
super super_instance;
void push(int value){
int newMin = std::min(value, this->min());
// Why are you using new? It would make
// It more difficult to avoid memory leaks
super_instance.push({value, newMin});
};
The third problem is stack
has no member function called isEmpty
, and neither does your class. stack
doesn't have a peek
member function either.
int min(){
if(super_instance.empty()){
return std::numeric_limits<int>::max();
}else{
return super_instance.top().min;
}
};
Now it will compile:
int main(int argc, const char * argv[])
{
StackWithMin<class NodeWithMin>* ss;
ss = new StackWithMin<class NodeWithMin>();
ss->push(42);
delete ss;
}
I did not bother checking for logic errors.
Upvotes: 2
Reputation: 1361
#include <stack>
#include <limits>
using namespace std;
class NodeWithMin{
public:
int value;
int min;
NodeWithMin(int v, int min){
this->value = v;
this->min = min;
}
};
template<class NodeWithMin>
class StackWithMin : stack<NodeWithMin>{
public:
typedef stack<NodeWithMin> super;
void push(int value){
int newMin = min(value, this->min());
super::push(new NodeWithMin(value, newMin));
};
int min(){
if(this->isEmpty()){
return numeric_limits<int>::max();
}else{
super::peek().min;
}
};
};
int main(int argc, const char * argv[])
{
StackWithMin<class NodeWithMin>* ss;
ss = new StackWithMin<class NodeWithMin>();
}
Please check this code segment, you had missed using namespace std
and you will have to include #include <limits>
to use numeric_limits<int>::max();
function.
Upvotes: 1