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


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


描述

C++ 函數std::array::cbegin()返回一個指向數組開頭的常量迭代器。此方法返回的迭代器可用於迭代容器,但不能用於修改數組內容。

聲明

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

const_iterator cbegin() const noexcept;

參數

返回值

返回指向數組開頭的常量迭代器。

異常

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

時間複雜度

常數,即 O(1)

示例

下麵的例子展示了 std::array::cbegin() 函數的用法。

#include <iostream>
#include <array>

using namespace std;

int main(void) {

   array<int, 5> arr = {1, 2, 3, 4, 5};
   auto it = arr.cbegin();

   /* iterate whole array */
   while (it < arr.end()) {
      cout << *it << " ";
      ++it;
   }

   cout << endl;

   return 0;
}

讓我們編譯並運行上麵的程序,這將產生以下結果 -

1 2 3 4 5 

由於此方法返回的是 const 迭代器,因此我們不能使用此迭代器來修改數組內容。任何修改數組元素的嘗試都會報告編譯錯誤。

#include <iostream>
#include <array>

using namespace std;

int main(void) {

   array<int, 5> arr = {1, 2, 3, 4, 5};
   auto it = arr.cbegin();   /* returns a constant iterator */

   /* ERROR:attemp to modify value will report compilation error */
   *it = 100;

   return 0;
}

上述程序的編譯將失敗並顯示以下錯誤消息。

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

相關用法


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