Change size of vector without destroying reserved elements

Using reserve() followed by push_back() 's may be faster than resizing the vector and later performing assignments -- as seen in std::vector reserve() and push_back() is faster than resize() and array index, why?.

However, if I make assignments instead of using push_back() , the size of the vector remains 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

}

Output:

8
SIZE: 0
0
SIZE: 10

How could I change the size of a vector, without destroying reserved entries? Of course, I still want to use reserve() , to reduce the cost of allocations -- I know the exact size I need.


When I want to avoid the value-initialization of vector elements, I use an allocator adaptor to remove exactly that behavior:

// 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)...);
  }
};

Types with trivial default initialization - like int - won't be initialized at all. (Live demo at Coliru)

链接地址: http://www.djcxy.com/p/79198.html

上一篇: 合并无额外内存的向量

下一篇: 在不破坏保留元素的情况下更改矢量的大小