C++ Deque::crbegin() 函式



C++ 的std::deque::crbegin()函式用於返回一個指向雙端佇列中最後一個元素的常量反向迭代器。此迭代器從雙端佇列的末尾到開頭遍歷雙端佇列,確保元素按反序訪問。它可用於以反序遍歷雙端佇列的元素,而無需更改其值。

常量迭代器防止修改其指向的元素,提供只讀訪問。

語法

以下是 std::deque::crbegin() 函式的語法。

const_reverse_iterator crbegin() const noexcept;

引數

它不接受任何引數。

返回值

它返回一個指向雙端佇列中最後一個元素的反向迭代器。

異常

此函式從不丟擲異常。

時間複雜度

此函式的時間複雜度為常數,即 O(1)。

示例

在以下示例中,我們將考慮 crbegin() 函式的基本用法。

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    std::deque<char>::const_reverse_iterator x = a.crbegin();
    std::cout << " " << *x << std::endl;
    return 0;
}

輸出

以上程式碼的輸出如下:

D

示例

考慮以下示例,我們將使用迴圈使用 crbegin() 和 crend() 以反序迭代雙端佇列。

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    for (auto x = a.crbegin(); x != a.crend(); ++x) {
        std::cout << *x << " ";
    }
    return 0;
}

輸出

以下是以上程式碼的輸出:

D C B A 

示例

讓我們看以下示例,我們將搜尋雙端佇列中的元素,同時以反序迭代。

#include <iostream>
#include <deque>
#include <algorithm>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    auto x = std::find(a.crbegin(), a.crend(), 'C');
    if (x != a.crend()) {
        std::cout << "Element found at position: " << std::distance(a.crbegin(), x) << std::endl;
    } else {
        std::cout << "Element not found." << std::endl;
    }
    return 0;
}

輸出

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

Element found at position: 1
deque.htm
廣告