使用reserve()
后跟push_back()
可能比调整矢量大小以及稍后执行分配更快 - 如std::vector reserve() and push_back() is faster than resize() and array index, why?中所示。
但是,如果我进行分配而不是使用push_back()
,则向量的大小仍为0
:
# include <vector>
int main() {
std::vector<int> x;
x.reserve(10);
x[0] = 10, x[1] = 9, x[2] = 8, x[3] = 7, x[4] = 6;
x[5] = 5, x[6] = 4, x[7] = 3, x[8] = 2, x[9] = 1;
std::cout << x[2] << std::endl;
std::cout << "SIZE: " << x.size() << std::endl; // 'size()' is 0
x.resize(10); // removes former entries, since the vector had 'size() = 0'
std::cout << x[2] << std::endl;
std::cout << "SIZE: " << x.size() << std::endl; // 'size()' is 10,
// but values are gone
}
输出:
8
SIZE: 0
0
SIZE: 10
如何在不破坏保留条目的情况下更改向量的大小?当然,我仍然想使用reserve()
来降低分配成本 - 我知道我需要的确切尺寸。
答案 0 :(得分:1)
当我想避免vector
元素的值初始化时,我使用分配器适配器来完全删除该行为:
// Allocator adaptor that interposes construct() calls to
// convert value initialization into default initialization.
template <typename T, typename A=std::allocator<T>>
class default_init_allocator : public A {
typedef std::allocator_traits<A> a_t;
public:
template <typename U> struct rebind {
using other =
default_init_allocator<
U, typename a_t::template rebind_alloc<U>
>;
};
using A::A;
template <typename U>
void construct(U* ptr) {
// value-initialization: convert to default-initialization.
::new (static_cast<void*>(ptr)) U;
}
template <typename U, typename...Args>
void construct(U* ptr, Args&&... args) {
// Anything else: pass through to the base allocator's construct().
a_t::construct(static_cast<A&>(*this),
ptr, std::forward<Args>(args)...);
}
};
具有普通默认初始化的类型 - 如int
- 根本不会被初始化。 (Live demo at Coliru)