std::arrayをいじって、 との違いを確認したかったのstd::vectorです。これまでのところ、大きな違いは 1 つしか見つかりませんでした。
Sentence sentence = { "Hello", "from", "GCC", __VERSION__, "!" };
std::array<std::string, 10> a;
std::copy(sentence.begin(), sentence.end(), a.begin());
int i = 0;
for (const auto& e : a)
{
i++;
std::cout << e << std::endl;
}
std::cout << i << std::endl;
// outputs 10
i = 0;
for (const auto& e : sentence)
{
i++;
std::cout << e << std::endl;
}
std::cout << i << std::endl;
// outputs 5
for (int i = 0; i < a.size(); i++)
std::cout << i << " " << a[i] << std::endl;
// outputs 0 Hello
// ...
// 4 !
// 5-9 is blank
for (int i = 0; i < sentence.size(); i++)
std::cout << i << " " << sentence[i] << std::endl;
// outputs 0 Hello
// ...
// 4 !
// stops here
// The following outputs the same as above
i = 0;
for (auto it = a.begin(); it != a.end(); it++)
{
std::cout << i << " " << *it << std::endl;
i++;
}
std::cout << i << std::endl;
i = 0;
for (auto it = sentence.begin(); it != sentence.end(); it++)
{
std::cout << i << " " << *it << std::endl;
i++;
}
std::cout << i << std::endl;
私が見る限り、とは冗長ですが、std::arrayとは同じでも異なっていてもかまいません。これは、この引用からも確認されます。sizemax_sizestd::vectorsizecapacity
配列オブジェクトの size と max_size は常に一致します。
では、なぜstd::array冗長なサイズ関数があるのでしょうか? さらに重要なことに、ベクトルには容量があるため、 のstd::arrayサイズが のサイズと必ずしも同じではないという落とし穴を考えますか? std::vectorまた、これはstd::arrays が安全であることを意味しますか (つまり、ベクトルのようなスマート ポインター管理がありますか?)