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
廣告