How take a element of the top of stack and put in a vector?

Hi, i don't getting take a element of stack and put in a vector. For example:

#include <iostream>
#include <stack>
#include <vector>

using namespace std;

int main()
{
stack<int> letter;
vector<int> put;

letter.push(69);
letter.push(56);
letter.push(66);
letter.push(33);
letter.push(23);
letter.push(44);



for(int i = 0; i < letter.size(); i ++){
put[i] = letter.top();
letter.pop();
}

vector<int>::iterator iter;

for(iter = put.begin(); iter != put.end(); iter++){
cout << *iter << endl;
}

return 0;
}
You have a few problems with the first loop.

Problem 1: You are removing elements from the stack (by calling pop()) and you are incrementing i so letter.size() and i will meet halfway.
i == 0, letter.size() == 6
i == 1, letter.size() == 5
i == 2, letter.size() == 4
i == 3, letter.size() == 3 // This breaks the loop


Problem 2: put is an empty vector so no elements can be accessed using index, put[i]. If you want to add an element to the end of a vector you can use the push_back function.
 
put.push_back(letter.top())

Note that you don't need to use the index i when using push_back.

http://www.cplusplus.com/reference/vector/vector/push_back/

Topic archived. No new replies allowed.