vector::front
ベクター内の最初の要素への参照を返します。
reference front( ); const_reference front( ) const;
戻り値
ベクター オブジェクト内の最初の要素への参照。 ベクターが空の場合、戻り値は未定義になります。
解説
front の戻り値が const_reference に割り当てられている場合、vector オブジェクトを変更することはできません。 front の戻り値が reference に割り当てられている場合、ベクター オブジェクトを変更できます。
_SECURE_SCL 1 でコンパイルする場合、空のベクター内の要素にアクセスしようとすると、ランタイム エラーが発生します。 詳細については、「チェックを行う反復子」を参照してください。
使用例
// vector_front.cpp
// compile with: /EHsc
#include <vector>
#include <iostream>
using namespace std;
int main( )
{
vector <int> vec;
vec.push_back(10);
vec.push_back(20);
int& i = vec.front();
const int& ci = vec.front();
cout << "The value of vec[0] is " << i << endl;
// front() returns a reference, not an iterator
// by incrementing i, we change the value of the first element
i++;
cout << "Now, the value of vec[0] is " << i << endl;
// ci++; compiler error because ci is const}
出力
The first integer of v1 is 10
Now, the first integer of v1 is 11
必要条件
ヘッダー: <vector>
名前空間: std