C++ Deque::cbegin() 函式



C++ 的 std::deque::cbegin() 函式用於返回指向第一個元素的常量迭代器,允許只讀訪問而不會修改容器。這對於迭代 deque 中的元素同時確保它們保持不變非常有用。它提供了一種安全且不可修改的方式來訪問 deque 開頭的元素。

語法

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

const_iterator cbegin() const noexcept;

引數

它不接受任何引數。

返回值

此函式返回指向序列開頭的 const_iterator。

異常

此函式從不丟擲異常。

時間複雜度

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

示例

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

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

輸出

以上程式碼的輸出如下:

A B C D 

示例

考慮以下示例,我們將使用 cbegin() 函式訪問第一個元素

#include <iostream>
#include <deque>
int main()
{
    std::deque<std::string> a = {"TutorialsPoint", "Tutorix", "TP"};
    std::cout << " " << *a.cbegin() << std::endl;
    return 0;
}

輸出

以上程式碼的輸出如下:

TutorialsPoint

示例

在下面的示例中,我們將使用 cbegin() 函式獲取常量迭代器並將第一個元素與值進行比較。

#include <iostream>
#include <deque>
int main()
{
    std::deque<char> a = {'A', 'B', 'C', 'D'};
    auto x = a.cbegin();
    if (*x == 'A') {
        std::cout << "First Element is equal to given value." << std::endl;
    } else {
        std::cout << "First Element is not equal to given value." << std::endl;
    }
    return 0;
}

輸出

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

First Element is equal to given value.
deque.htm
廣告