How to initialize vector from array without allocating more storage space?

前端 未结 2 882
忘掉有多难
忘掉有多难 2020-12-11 11:26

The direct way to initialize a vector from an array seems to be:

int sizeArr; int * array = getArray(sizeArr);
std::vector vec(array, array+sizeAr         


        
相关标签:
2条回答
  • 2020-12-11 11:50

    Why do you even allocate the memory with a pointer for int? There is a very high chance, that you have no reason for doing this.

    If you have a compiler which assists c++11 it should be possible to just initialize the vector with std::vector vec{array}; Or if you dont need the array anymore, just delete it and push references of the array to the vector

    0 讨论(0)
  • 2020-12-11 12:06

    If the caller doesn't own the data (i.e. is not in charge of deleting it), then the easiest option might be to write a container-like wrapper:

    template <typename T>
    struct array_wrapper
    {
      typedef T* iterator;
      typedef const T* const_iterator;
      array_wrapper(T* begin, T* end) : data_(begin), size_(end-begin) {}
      iterator begin() { return data_; }
      iterator end() { return data_ + size_; }
      const_iterator begin() const { return data_; }
      const_iterator end() const { return data_ + size_; }
      size_t size() const { return size_; }
      T& operator[](size_t i) { return _data[i]; }
      const T& operator[](size_t i) const { return _data[i]; }
      void swap(array_wrapper& other) { 
        std::swap(size_, other.size_);
        std::swap(data_, other.data_);
      }
     private:
      T* data_;
      size_t size_;
    };
    

    then

    array_wrapper<int> vec(array, array+sizeArr);
    

    This has a lot of the functionality of an std::vector, but does not own the underlying data, and supports no operations that would result in resizing or re-allocating.

    0 讨论(0)
提交回复
热议问题