C++ 在不破坏保留元素的情况下更改向量的大小
使用C++ 在不破坏保留元素的情况下更改向量的大小,c++,memory-management,vector,C++,Memory Management,Vector,使用reserve()后跟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]
reserve()
后跟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
}
如何在不破坏保留项的情况下更改向量的大小?当然,我仍然希望使用
reserve()
,以降低分配成本--我知道我需要的确切大小。当我希望避免向量
元素的值初始化时,我使用分配器适配器来准确地删除该行为:
// 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)...);
}
};
//将construct()调用插入到
//将值初始化转换为默认初始化。
模板
类默认\u初始化\u分配器:公共A{
typedef std::allocator_traits)请阅读文档:vector::reserve只是为请求的数量保留容量-内存是统一的如果您使用c++11,您可以执行std::vector x{10,9,…}
@DieterLück内存未初始化,但还是分配了,不是吗?还是仍为push_back()保留分配
?另外,如果您知道所需的确切大小,为什么不使用std::array
?编辑:根据,在所有其他情况下,函数调用不会导致重新分配,并且向量容量不会受到影响。@Gasim我正在编写一个小型序列化程序。用户打包了一个向量,并将其大小写入缓冲区。我知道在执行过程中的确切大小解包,但我仍然在处理vector
+1谢谢你的支持!我想这是我想要的最好的选择——只希望它更简单(:Edit:ah,我的错!我不能更改向量结构,因为它是由用户提供的(我正在编写一个简单的序列化程序)。@Rubens如果Boost是你的选择。
// 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)...);
}
};