简体   繁体   English

c++ 矢量效率

[英]c++ Vector efficiency

The standard requires that vector implementations can efficiently add elements at run time.该标准要求向量实现可以在运行时有效地添加元素。 Because vectors grow efficiently, it is often unnecessary—and can result in poorer performance—to define a vector of a specific size.因为向量有效地增长,所以通常没有必要——并且可能导致更差的性能——定义一个特定大小的向量。 The exception to this rule is if all the elements actually need the same value.此规则的例外是所有元素实际上都需要相同的值。 If differing element values are needed, it is usually more efficient to define an empty vector and add elements as the values we need to become known at run time.如果需要不同的元素值,通常更有效的是定义一个空向量并添加元素作为我们需要在运行时知道的值。

Reading in C++ prime (C++ 11 edition).阅读 C++ prime(C++ 11 版)。 Can someone explain to me why does that happens to be the case.有人可以向我解释为什么会发生这种情况。 I mean imagine we need to add somewhere 1 million different numbers into the std::vector.我的意思是想象我们需要在 std::vector 中添加 100 万个不同的数字。 Why is that if I push_back them into the vector which hasn't defined approximate size will be the more "efficient" way than defining the size ?为什么如果我将它们 push_back 放入未定义近似大小的向量中,将是比定义大小更“有效”的方式 I mean I have a vague understanding of vector size and capacity and I believe every time Vector exceeds its capacity all the elements are copied into the bigger size array (n * 2 or n * 1.5 somewhere the neighborhood)...我的意思是我对向量的大小和容量有一个模糊的理解,我相信每次 Vector 超过它的容量时,所有元素都会被复制到更大的数组中(n * 2 或 n * 1.5 附近的某个地方)......

For simple types such as ints, declaring a vector with the number of elements needed will likely be faster than using push_back , because the vector won't need to do any reallocations.对于 int 等简单类型,声明具有所需元素数量的向量可能比使用push_back更快,因为向量不需要进行任何重新分配。 However, with complex classes which have constructors, doing so will default-construct all the elements and then overwrite them, wasting time.但是,对于具有构造函数的复杂类,这样做会默认构造所有元素,然后覆盖它们,浪费时间。

In both cases, the best solution would be to use reserve to allocate space for all the elements at once without constructing those elements.在这两种情况下,最好的解决方案是使用reserve一次性为所有元素分配空间,而不构建这些元素。 Then you can use push_back without worrying about reallocations.然后您可以使用push_back而不必担心重新分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM