std :: vectorに2つの演算子が含まれているのはなぜ[]
ですか?
reference operator[]( size_type pos );
const_reference operator[]( size_type pos ) const;
1つは非constベクトルオブジェクト用で、もう1つはconstベクトルオブジェクト用です。
void f(std::vector<int> & v1, std::vector<int> const & v2)
{
//v1 is non-const vector
//v2 is const vector
auto & x1 = v1[0]; //invokes the non-const version
auto & x2 = v2[0]; //invokes the const version
v1[0] = 10; //okay : non-const version can modify the object
v2[0] = 10; //compilation error : const version cannot modify
x1 = 10; //okay : x1 is inferred to be `int&`
x2 = 10; //error: x2 is inferred to be `int const&`
}
ご覧のとおり、非constバージョンでは、インデックスを使用してベクトル要素を変更できますが、const
バージョンではベクトル要素を変更できません。これが、これら2つのバージョンの意味上の違いです。
詳細な説明については、次のFAQを参照してください。
お役に立てば幸いです。
この差別化を可能にするには:
// const vector object, cannot be modified
// const operator[] allows for this
int get_value(const std::vector<int>& vec, size_t index)
{
return vec[index];
}
// non-const vector object can be modified
// non-const operator[] allows for this
void set_value(std::vector<int>& vec, size_t index, int val)
{
vec[index] = value;
}
std::vector<int> values;
values.push_back(10);
values.push_back(20);
set_value(values, 0, 50);
get_value(values, 0);
1つは、(非const)ベクトルを変更して読み取ることができるようにするためです。
void foo( std::vector<int>& vector )
{
// reference operator[]( size_type );
int old = vector[0];
vector[0] = 42;
}
constベクトルから読み取ることができるようにするための1つ
void foo( std::vector<int> const& vector )
{
//const_reference operator[]( size_type ) const;
int i = vector[0];
}
2つのオーバーロードの1つを使用すると、変数const
を介してアクセスされるベクトルの要素への参照を取得できます。const
もう1つは、非変数const
を介してアクセスされるベクトルの要素への非参照を取得できるようにします。const
バージョンがない場合const
、たとえば次のものをコンパイルすることはできません。
void f(vector<int> const& v)
{
cout << v[0]; // Invokes the const version of operator []
}
次の例では、代わりに、non-constバージョンが呼び出されます。これconst
により、配列の最初の要素への非参照が返され、たとえば、新しい値を割り当てることができます。
void f(vector<int>& v)
{
v[0] = 1; // Invokes the non-const version of operator[]
}