C++ Queue::back() 函式



C++ 的std::queue::back()函式用於訪問佇列的最後一個元素,而無需將其移除。它允許訪問最近新增的元素,提供了一種讀取或修改該元素的方法。此函式的時間複雜度為O(1)。當需要修改佇列中最近新增的元素時,通常會使用此函式。

當此函式在空佇列上呼叫時,會導致未定義行為。

語法

以下是std::queue::back()函式的語法。

reference& back();const_reference& back() const;

引數

此函式不接受任何引數。

返回值

此函式返回對佇列中最後一個元素的引用。

示例

讓我們來看下面的例子,我們將演示back()函式的基本用法。

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    a.push(11);
    a.push(22);
    a.push(33);
    std::cout << "The last element is: " << a.back() << std::endl;
    return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

The last element is: 33

示例

考慮另一種情況,我們將使用back()函式修改最後一個元素。

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    a.push(1);
    a.push(2);
    a.back() = 11;
    std::cout << "After modification the last element is : " << a.back() << std::endl;
    return 0;
}

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

After modification the last element is : 11

示例

在下面的示例中,我們將back()函式用於迴圈。

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    for (int x = 1; x <= 5; ++x) {
        a.push(x * 2);
        std::cout << "" << a.back() << std::endl;
    }
    return 0;
}

輸出

以上程式碼的輸出如下:

2
4
6
8
10

示例

下面的示例中,我們首先檢查佇列是否為空,然後向佇列新增元素並應用back()函式。

#include <iostream>
#include <queue>
int main()
{
    std::queue<int> a;
    if (!a.empty()) {
        std::cout << "The last element is: " << a.back() << std::endl;
    } else {
        std::cout << "The queue is empty" << std::endl;
    }
    a.push(1);
    a.push(2);
    if (!a.empty()) {
        std::cout << "After adding elements, the last element is: " << a.back() << std::endl;
    }
    return 0;
}

輸出

如果我們執行上面的程式碼,它將生成以下輸出:

The queue is empty
After adding elements, the last element is: 2
queue.htm
廣告