名稱空間
變體
操作

std::end, std::cend

來自 cppreference.com
 
 
迭代器庫
迭代器概念
迭代器原語
演算法概念與工具
間接可呼叫概念
常用演算法要求
(C++20)
(C++20)
(C++20)
工具
(C++20)
迭代器介面卡
範圍訪問
(C++11)(C++14)
(C++14)(C++14)  
endcend
(C++11)(C++14)
(C++14)(C++14)  
(C++17)(C++20)
(C++17)
(C++17)
 
定義於標頭檔案 <array>
在標頭檔案 <deque> 中定義
在標頭檔案 <flat_map> 中定義
在標頭檔案 <flat_set> 中定義
在標頭檔案 <forward_list> 中定義
在標頭檔案 <inplace_vector> 中定義
定義於標頭檔案 <iterator>
定義於標頭檔案 <list>
定義於標頭檔案 <map>
在標頭檔案 <regex> 中定義
在標頭檔案 <set> 中定義
在標頭檔案 <span> 中定義
定義於標頭檔案 <string>
定義於標頭檔案 <string_view>
在標頭檔案 <unordered_map> 中定義
定義於標頭檔案 <unordered_set>
在標頭檔案 <vector> 中定義
template< class C >
auto end( C& c ) -> decltype(c.end());
(1) (C++11 起)
(自 C++17 起為 constexpr)
template< class C >
auto end( const C& c ) -> decltype(c.end());
(2) (C++11 起)
(自 C++17 起為 constexpr)
template< class T, std::size_t N >
T* end( T (&array)[N] );
(3) (C++11 起)
(自 C++14 起 noexcept)
(C++14 起為 constexpr)
template< class C >

constexpr auto cend( const C& c ) noexcept(/* 見下文 */)

    -> decltype(std::end(c));
(4) (C++14 起)

返回給定範圍的末尾(即最後一個元素之後的元素)的迭代器。

1,2) 返回 c.end(),它通常是序列 c 末尾之後的一個迭代器。
1) 如果 C 是標準容器,則返回 C::iterator 物件。
2) 如果 C 是標準容器,則返回 C::const_iterator 物件。
3) 返回指向 array 末尾的指標。
4) 返回 std::end(c),其中 c 始終被視為 const 限定。
如果 C 是標準容器,則返回 C::const_iterator 物件。

range-begin-end.svg

目錄

[edit] 引數

c - 一個具有 end 成員函式的容器或檢視
array - 任意型別的陣列

[edit] 返回值

1,2) c.end()
3) array + N
4) c.end()

[edit] 異常

4)
noexcept 規範:  
noexcept(noexcept(std::end(c)))

[edit] 過載

對於沒有公開合適的 end() 成員函式但可迭代的類和列舉,可以提供 end 的自定義過載。標準庫已提供以下過載

特化 std::end
(函式模板) [edit]
特化 std::end
(函式模板) [edit]
支援基於範圍的 for 迴圈
(函式) [edit]
支援基於範圍的 for 迴圈
(函式) [edit]

與使用 swap(在可交換中描述)類似,在泛型上下文中 end 函式的典型用法等同於 using std::end; end(arg);,這使得使用者定義型別的 ADL 選擇過載和標準庫函式模板都出現在同一個過載集中。

template<typename Container, typename Function>
void for_each(Container&& cont, Function f)
{
    using std::begin;
    auto it = begin(cont);
    using std::end;
    auto end_it = end(cont);
 
    for (; it != end_it; ++it)
        f(*it);
}

透過依賴於引數的查詢找到的 end 的過載可以用於自定義 std::ranges::endstd::ranges::cend 以及其他依賴於 std::ranges::end 的自定義點物件的行為。

(C++20 起)

[edit] 備註

非陣列過載精確反映了 C::end() 的行為。如果成員函式沒有合理的實現,其效果可能會令人驚訝。

引入 std::cend 是為了統一成員和非成員範圍訪問。另請參閱 LWG issue 2128

如果 C 是淺 const 檢視,std::cend 可能會返回一個可變迭代器。這種行為對某些使用者來說是出乎意料的。另請參閱 P2276P2278

[edit] 示例

#include <algorithm>
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> v = {3, 1, 4};
    if (std::find(std::begin(v), std::end(v), 5) != std::end(v))
        std::cout << "Found a 5 in vector v!\n";
 
    int w[] = {5, 10, 15};
    if (std::find(std::begin(w), std::end(w), 5) != std::end(w))
        std::cout << "Found a 5 in array w!\n";
}

輸出

Found a 5 in array w!

[edit] 參閱

(C++11)(C++14)
返回指向容器或陣列開頭的迭代器
(函式模板) [edit]
返回指示範圍末尾的哨兵
(自定義點物件)[edit]
返回一個表示只讀範圍末尾的哨兵
(自定義點物件)[edit]