我想和std::array混在一起,看看它和std::vector有多大的不同。到目前为止,我只发现了一个主要的区别。
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的size和max_size是多余的,但std::vector的size和capacity可能是不同的,也可能是相同的。这一点甚至可以从这句话中得到证实:
数组对象的大小和max_size总是匹配的。
那么,为什么std::array有冗余大小函数呢?更重要的是,您是否认为std::array的大小不一定与std::vector的大小相同,因为向量具有容量?这是否意味着std::arrays是安全的(也就是说,它们有像向量一样的智能指针管理?)
发布于 2013-05-05 02:28:19
稍微扩展一下,关于这个主题,std::array非常接近于数组的实际设计,比如char[],其中数组的最大大小就是数组的大小。这是因为数组可以被认为具有不可变的大小。这是一个大小是不能改变的,除了完全重新分配内存。与std::vector不同,后者可以设置为具有capacity,大小可以从0到该capacity,但是,一旦传递capacity值,每个新元素将导致vector内部的底层数组的完整重新分配。
https://stackoverflow.com/questions/16380740
复制相似问题