名稱空間
變體
操作

std::span<T,Extent>::begin, std::span<T,Extent>::cbegin

來自 cppreference.com
< cpp‎ | 容器‎ | span
constexpr iterator begin() const noexcept;
(1) (C++20 起)
constexpr const_iterator cbegin() const noexcept;
(2) (C++23 起)

返回 span 的第一個元素的迭代器。

如果 span 為空,則返回的迭代器將等於 end()

range-begin-end.svg

目錄

[編輯] 返回值

指向第一個元素的迭代器。

[編輯] 複雜度

常數時間。

[編輯] 示例

#include <iostream>
#include <span>
 
void print(std::span<const int> array)
{
    std::cout << "array = ";
    for (auto it = array.begin(); it != array.end(); ++it)
        std::cout << *it << ' ';
    std::cout << '\n';
}
 
void set_first_element(std::span<int> sp, int new_value)
{
    if (!sp.empty())
    {
        std::cout << "old *begin = " << *sp.begin() << '\n';
        *sp.begin() = new_value;
        std::cout << "new *begin = " << *sp.begin() << '\n';
    }
}
 
int main()
{
    int array[]{1, 3, 4, 5};
    print(array);
    set_first_element(array, 2);
    print(array);
}

輸出

array = 1 3 4 5
old *begin = 1
new *begin = 2
array = 2 3 4 5

[編輯] 參閱

(C++23)
返回指向末尾的迭代器
(public member function) [編輯]
(C++11)(C++14)
返回指向容器或陣列開頭的迭代器
(function template) [編輯]