在不破坏保留元素的情况下更改矢量的大小
使用reserve()
后跟push_back()
的方法可能会比调整矢量大小和后续执行的任务要快 - 正如在std :: vector reserve()和push_back()中所看到的那样,它比resize()和数组索引快,为什么? 。
但是,如果我使用push_back()
进行分配而不是使用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()
来减少分配的成本 - 我知道我需要的确切大小。
当我想要避免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
- 根本不会被初始化。 (在Coliru现场演示)
上一篇: Change size of vector without destroying reserved elements