-2

I need to simulate the stack using Qt, as elements which can be used for the int and string. I don't need your code, but i have literally no idea how to do it. I will be grateful for any tips.

Murad
  • 155
  • 2
  • 6
  • Any reason why you cannot use the QStack class which is already there? – tofro Feb 23 '16 at 19:29
  • @tofro "QStack is one of Qt's generic container classes. It implements a stack data structure for items of a same type." but i need stack, which may contain both int and string elements. – Murad Feb 23 '16 at 19:32
  • provide an interface for anything you want to do with the objects while they are on the stack and then implement it for `int` and for `string` – 463035818_is_not_an_ai Feb 23 '16 at 19:41
  • The simple answer is create a wrapper that could contain a `string` or an `int`, but I call X-Y ([What is the X-Y problem?](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)). What are you really trying to use this stack for? Maybe someone can suggest something better. – user4581301 Feb 23 '16 at 19:43
  • Why do you need to put ints and strings onto the same stack? Actually this smells like a ["xy problem"](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – 463035818_is_not_an_ai Feb 23 '16 at 19:45
  • @tobi303 my friend get this task in university. – Murad Feb 23 '16 at 19:46
  • sry but I have my doubts, that the exercise is worded like this (because the solution is a 2 liner), you should tell us what is the actual problem that you are trying to solve. On the other hand, if this is really the assignment, you should take it as an exercise to find it out yourself. – 463035818_is_not_an_ai Feb 23 '16 at 19:53
  • Stacking different things on the same stack has a very considerable flaw: You need to know what type is on top the stack before you can actually pop it. This is why everyone tells you "better not" – tofro Feb 24 '16 at 11:08

1 Answers1

1

You can use a QStack<QVariant> to achieve the result you want.

#include <QtCore/QStack>
#include <QtCore/QVariant>

int main( int argc, char* argv[] )
{
   QStack<QVariant> stack;

   stack.push_back( 1 );
   stack.push_back( "two" );

   std::cout << stack.pop().toInt() << " " 
             << stack.pop().toString().toStdString() << std::endl; 
}

which gives

1 two
Thomas
  • 4,980
  • 2
  • 15
  • 30
  • If the purpose is "get a result in a quick and dirty way", that is probably a perfect solution. For production code (I doubt we go for that), I would consider QVariant way too heavyweight. A better solution (especially if we are going for a learning experience, which I think is the case here) IMHO would be a template class StackableItem that has only the required setters and getters. – tofro Feb 24 '16 at 11:04