initialize member list for stack

Hi,

I know vector & array containers are more suited for this, but I want to know how to initialize stack container with member list, if possible. If its in the ref I must have missed it.

http://www.cplusplus.com/reference/stack/stack/

1
2
3
4
5
6
7
8
9
10
11

#include<iostream>
#include<stack>
using namespace std;
int main()
{
	std::stack<int>Stack;
	Stack {3,4,5,6};

}


error:


.\src\main.cpp:7:8: error: expected ';' before '{' token
  Stack {3,4,5,6;};
Last edited on
Hi,

std::stack does not have a constructor for std::initializer_list

But using a variation of range based for does the same thing :+)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<stack>
//using namespace std;
int main()
{
	std::stack<int>Stack;
	//Stack {3,4,5,6};
    for (auto& item : {3,4,5,6}) {
        Stack.push(item);
    }
    
    std::cout << "Stack contents are:\n";
    for (const auto& item : {3,4,5,6}) {
         std::cout << item << " ";
    }
}



Stack contents are:
3 4 5 6  
I would think the second loop should print directly from the stack itself rather then just the same member list :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<iostream>
#include<stack>
//using namespace std;
int main()
{
	std::stack<int>Stack;
	//Stack {3,4,5,6};
    for (auto& item : {3,4,5,6}) {
        Stack.push(item);
    }
    
    std::cout << "Stack contents are:\n";
    while( !Stack.empty() )
    {
        std::cout << Stack.top() << " ";
        Stack.pop();
    }
}


Stack contents are:
6 5 4 3  
Last edited on
@Arslan7041

My Bad !! !FacePalm!

I was discombobulated: std::stack does not have begin and end iterators, so ranged based for loop was never going to work for printing the contents.
Topic archived. No new replies allowed.