是否有C ++函数对std :: stack进行排序?

问题描述 投票:3回答:1

我的代码中有一个std::stack,我需要对其进行排序。有内置的功能可以做到这一点吗?由于std::stack没有std::end。我可以使用std::sort还是必须使用使用辅助堆栈对原始堆栈进行排序的相同旧方法?

c++ sorting stl stack
1个回答
0
投票
#include <bits/stdc++.h> 
using namespace std; 

// This function return the sorted stack 
stack<int> sortStack(stack<int> &input) 
{ 
    stack<int> tmpStack; 

    while (!input.empty()) 
    { 
        // pop out the first element 
        int tmp = input.top(); 
        input.pop(); 

        // while temporary stack is not empty and top 
        // of stack is greater than temp 
        while (!tmpStack.empty() && tmpStack.top() < tmp) 
        { 
            // pop from temporary stack and push 
            // it to the input stack 
            input.push(tmpStack.top()); 
            tmpStack.pop(); 
        } 

        // push temp in tempory of stack 
        tmpStack.push(tmp); 
    } 

    return tmpStack; 
} 

// main function 
int main() 
{ 
    stack<int> input; 
    input.push(34); 
    input.push(3); 
    input.push(31); 
    input.push(98); 
    input.push(92); 
    input.push(23); 

    // This is the temporary stack 
    stack<int> tmpStack = sortStack(input); 
    cout << "Sorted numbers are:\n"; 

    while (!tmpStack.empty()) 
    { 
        cout << tmpStack.top()<< " "; 
        tmpStack.pop(); 
    } 
} 

输出:

排序的数字是:3 23 31 34 92 98

© www.soinside.com 2019 - 2024. All rights reserved.