C++ 数组::front() 函数



C++ 的std::array::front()函数用于返回数组第一个元素的引用,允许进行读写操作。

当在空数组上调用 front() 函数时,会导致未定义行为。

语法

以下是 std::array::front() 函数的语法。

reference front();
const_reference front() const;

参数

它不接受任何参数。

返回值

它返回数组的第一个元素。

异常

在空数组容器上调用此方法会导致未定义行为。

时间复杂度

常数,即 O(1)

示例 1

在下面的示例中,我们将考虑 front() 函数的基本用法。

#include <iostream>
#include <array>
using namespace std;
int main(void) {
   array < int, 5 > arr = {10,20,30,40,50};
   cout << "First element of array = " << arr.front() <<
      endl;
   arr.front() = 1;
   cout << "After modification first element of array = " << arr.front() <<
      endl;
   return 0;
}

输出

以上代码的输出如下:

First element of array = 10
After modification first element of array = 1

示例 2

考虑下面的示例,我们将声明一个没有大小的数组并观察输出。

#include <iostream>
#include <array>
using namespace std;
int main() {
   array < char >
      myarray {'a','b','c','d','e','f','g'};
   cout << myarray.front();
   return 0;
}

输出

以上代码的输出如下:

main.cpp: In function 'int main()':
main.cpp:6:19: error: wrong number of template arguments (1, should be 2)
    6 |         array<char>
      |                   ^
In file included from main.cpp:2:
/usr/include/c++/11/array:95:12: note: provided for 'template<class _Tp, long unsigned int _Nm> struct std::array'
   95 |     struct array
      |            ^~~~~
main.cpp:7:9: error: scalar object 'myarray' requires one element in initializer
    7 |         myarray{ 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
      |         ^~~~~~~
array.htm
广告

© . All rights reserved.