C++ Array::begin() 函式



C++ 的 std::array::begin() 函式用於返回指向陣列第一個元素的迭代器。它允許從陣列的開頭遍歷或操作元素。

此函式可用於常量和非常量上下文,這意味著它有兩個過載:一個返回常量迭代器,另一個返回非常量迭代器。

語法

以下是 std::array::begin() 函式的語法。

iterator begin() noexcept;
const_iterator begin() const noexcept;

引數

它不接受任何引數。

返回值

此函式返回指向序列開頭的迭代器。

異常

此函式從不丟擲異常。

時間複雜度

常數,即 O(1)

示例 1

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

#include <iostream>
#include <array>
using namespace std;
int main(void) {
   array < int, 5 > arr = {1,2,3,4,5};
   auto itr = arr.begin();
   while (itr != arr.end()) {
      cout << * itr << " ";
      ++itr;
   }
   cout << endl;
   return 0;
}

輸出

上述程式碼的輸出如下:

1 2 3 4 5

示例 2

考慮另一個示例,我們將對字元陣列使用 begin() 函式。

#include <iostream>
#include <array>
using namespace std;
int main() {
   array < char, 5 > myarray {'P','R','A','S','U'};
   for (auto it = myarray.begin(); it != myarray.end(); ++it)
      cout << ' ' << * it;
   return 0;
}

輸出

以下是上述程式碼的輸出:

P R A S U
array.htm
廣告