溫馨提示×

如何在c++中自定義stack類的比較函數(shù)

c++
小樊
81
2024-09-25 07:25:12
欄目: 編程語言

在C++中,可以通過提供自定義的比較函數(shù)來定制stack類的行為。這通常是通過使用std::stack的模板參數(shù)和提供一個自定義的比較對象來實(shí)現(xiàn)的。下面是一個示例,展示了如何創(chuàng)建一個自定義比較函數(shù)并將其用于std::stack

首先,定義一個自定義比較函數(shù),例如:

#include <iostream>
#include <functional>
#include <stack>

// 自定義比較函數(shù)
struct CustomCompare {
    bool operator()(const int& a, const int& b) const {
        return a > b; // 實(shí)現(xiàn)降序排列
    }
};

接下來,創(chuàng)建一個使用自定義比較函數(shù)的std::stack實(shí)例:

int main() {
    // 使用自定義比較函數(shù)創(chuàng)建一個整數(shù)棧
    std::stack<int, std::vector<int>, CustomCompare> myStack;

    // 向棧中添加元素
    myStack.push(5);
    myStack.push(3);
    myStack.push(8);
    myStack.push(1);

    // 打印棧中的元素
    while (!myStack.empty()) {
        std::cout << ' ' << myStack.top();
        myStack.pop();
    }
    std::cout << std::endl;

    return 0;
}

在這個示例中,我們創(chuàng)建了一個名為CustomCompare的結(jié)構(gòu)體,它實(shí)現(xiàn)了operator(),用于比較兩個整數(shù)。然后,我們將這個自定義比較函數(shù)作為模板參數(shù)傳遞給std::stack,以便在棧中實(shí)現(xiàn)降序排列的元素。

0