I need to change my bubble sort (void stekas) to something called stack. Thing is that in file there are numbers and I need to sort them to rising order. I did good with bubble sort, but I have no idea how I should do that using stack. Any ideas?
You can't sort a stack because you can access only the top element. What you could do is copy all the elements from the stack into the array, sort the array and copy the array elements from the array to the stack. However if you need the elements sorted a stack might not be right container.
Is there a reason why you don't use vector and std::sort ?
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <algorithm>
usingnamespace std;
int main()
{
stack<int> s;
vector<int>v;
// create a unsorted stack
for (int i: {1, 5, 3, 7, 2})
s.push(i);
// bring the numbers into the vector
while (!s.empty())
{
v.push_back(s.top());
s.pop();
}
// sort the vector
sort(v.begin(), v.end());
// add the numbers from the vector to the stack
for (int i: v)
s.push(i);
// stack now should be sorted
while (!s.empty())
{
cout << s.top() << "\t";
s.pop();
}
}