私はstd :: vector of C++を学習しています。 std :: vectorのoperator []に2つの問題があります。私はオペレータ[]でのstd :: vecotrの値n番目を設定仮定C++でstd :: vectorのn番目の値をoperator []で正しく設定できますか?
、
(1)値n番目の前の要素が初期化されていません。
(2)n番目の値は演算子[]で設定できますが、サイズと反復子は正しく変更されません。
以下はテストコードです。
/* Test class : its has only id_ and it can print it. */
class Tmp {
public :
Tmp(int new_id) : id_(new_id) {
std::cout << "class Tmp constructor. id = " << id_ << std::endl;
}
void print(void) {
std::cout << "id = " << id_ << std::endl;
}
private :
int id_ = 777;
};
std::vector<Tmp> b;
b.reserve(1);
/* push_back() automatically expands buffer of std::vector. */
b.push_back(Tmp(1));
b.push_back(Tmp(2));
b.push_back(Tmp(3));
b.push_back(Tmp(4));
b.push_back(Tmp(5));
std::cout << "Before operator[] : size = " << b.size() << ", capacity = " << b.capacity() << std::endl;
/* I set the 7 th value. */
b[6] = Tmp(7);
b[6].print();
/* Operator[6] does not change size of std::vector. */
std::cout << "Before operator[] : size = " << b.size() << ", capacity = " << b.capacity() << std::endl;
/* Operator[6] did not expand iterator of std::vector correctly. */
for (auto it = b.begin(); it != b.end(); ++it) {
it->print();
}
その出力、
class Tmp constructor. id = 1
class Tmp constructor. id = 2
class Tmp constructor. id = 3
class Tmp constructor. id = 4
class Tmp constructor. id = 5
Before operator[] : size = 5, capacity = 8
class Tmp constructor. id = 7
id = 7
After operator[] : size = 5, capacity = 8
id = 1
id = 2
id = 3
id = 4
id = 5
私はオペレータ[N]によってN番目のstd ::の値ベクトルを設定することができ、以下の通りでありますか? 私はそれを行うことができます、どのようにn番目の値の前に値を初期化できますか?
ありがとうございました。
なぜ 'vector <> :: operator []'はサイズを変更すると思いますか? –
'operator []'で新しい要素を作成することはできません。既存の要素を更新する場合にのみ使用できます。 from http://www.cplusplus.com/reference/vector/vector/operator[]/ **ポータブルプログラムは、未定義の動作を引き起こすので、範囲外の引数nでこの関数を呼び出さないでください。** – Barmar
'operator []'へのすべての呼び出しを '.at()'に置き換えることができます。何が起こるかを見てください。 –