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
广告
© . All rights reserved.