I wanted to mess around with std::array
to see how different it is from std::vector
. So far, I've only found one major difference.
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;
So from what I can see, std::array
's size
and max_size
is redundant, but std::vector
's size
and capacity
can be different or the same. This is even confirmed from this quote:
size and max_size of an array object always match.
So why does std::array
have redundant size functions? More importantly, would you consider it a gotcha that std::array
's size is not necessarily the same as std::vector
's size, because the vector has a capacity? Also, does this mean that std::array
s are safe (i.e., do they have smart pointer management like vectors?)