當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Array cend()用法及代碼示例


描述

C++ 函數std::array::cend()返回一個指向數組的 past-end 元素的常量迭代器。此方法返回的迭代器可用於迭代數組內容,但不能用於修改數組內容,即使數組對象本身不是常量。

聲明

以下是 std::array::cend() 函數形式 std::array 標頭的聲明。

const_iterator cend() const noexcept;

參數

返回值

返回指向數組的 past-end 元素的常量迭代器。這是一個 place-holder 位置,不存儲任何實際數據。因此,取消引用 this 將導致未定義的行為。

異常

此成員函數從不拋出異常。

時間複雜度

常數,即 O(1)

示例

讓我們嘗試修改 const 迭代器指向的值。

#include <iostream>
#include <array>

using namespace std;

int main(void) {

   array<int, 5> arr = {10, 20, 30, 40, 50};
   auto it = arr.cend(); /* iterator pointing to past−the−end of array */

   /* ERROR:attempt to modification will cause compilation error */
   *it = 5;

   return 0;
}

上麵的程序產生以下錯誤信息。

cend.cpp:In function ‘int main()’:
cend.cpp:12:8:error:assignment of read-only location ‘* it’
   *it = 5;
      ^

相關用法


注:本文由純淨天空篩選整理自 C++ Array Library - cend() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。