ExtremistEnigma ExtremistEnigma - 2 months ago 11
C++ Question

C++ - Nested containers (list container of stack containers)

I want to create a linked list of stack objects using STL. This is how my code looks like:

int main() {
stack<int> s1;
list<stack<int>> ll;
s1.push(0)
ll.push_back(s1);
auto it = ll.begin();
it++;
cout << *it->top() << endl;
return 0;
}


The errors I get are illegal indirection and '<<' illegal for class on the second last line. What seems to be the issue? Thanks.

Answer

You want your line to read as follows:

cout << (*it).top() << endl;

You were dereferencing the value instead of a pointer to the value. Notice that I changed the -> to a . The nuts and bolts are that 'it' is essentially a pointer to your value and '*it' gives you the value so when you want to access members of that value you need a . instead of a ->

Update: Also, as was pointed out by others, there is a missing ; after the push and you've only added one item to the list and then incremented your iterator which positions you at the end of the list, after the one value. This will cause you run time problems.