在std::vector末尾插入几个值最好是什么?

What is best to insert several values at the end of a std::vector?

std::vector<int> v 添加元素是否更好:

// Read and manipulate a, b, c triplet as ints.
// Potentially also: v.reserve(v.size() + 3); or trust vector growth policy?
v.push_back(a);
v.push_back(b);
v.push_back(c);

v.insert(v.end(), {a, b, c});

从性能的角度来看(假设我们总是要插入每次都不同的三元组,并且它们的数量很大,比如 100 万个三元组)?感谢提示。

首先,在循环中执行 v.reserve(v.size() + 3); 通常是一个非常糟糕的主意,因为它肯定会导致每次迭代都进行新的重新分配。例如,带有 libstdc++ 和 libc++ 的 Clang 和 GCC 实际上都进行了线性数量的重新分配(参见 here, here or even there). Here is a quote from cppreference:

Correctly using reserve() can prevent unnecessary reallocations, but inappropriate uses of reserve() (for instance, calling it before every push_back() call) may actually increase the number of reallocations (by causing the capacity to grow linearly rather than exponentially) and result in increased computational complexity and decreased performance. For example, a function that receives an arbitrary vector by reference and appends elements to it should usually not call reserve() on the vector, since it does not know of the vector's usage characteristics.
When inserting a range, the range version of insert() is generally preferable as it preserves the correct capacity growth behavior, unlike reserve() followed by a series of push_back()s.
reserve() cannot be used to reduce the capacity of the container; to that end shrink_to_fit() is provided.

当谈到insert VS push_backs时,insert应该比许多push_back稍微好一些,因为容量检查只能做一次而不是多个 push_back。也就是说,性能差异在很大程度上取决于标准库的实现。