Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

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

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

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

Here, I am getting the array from a function which allocates the space in memory and sets sizeArr by reference. {start edit} Unfortunately, the function is not written by me and I need to deal with C style array then convert it to a vector somehow. (If possible efficiently). {end edit}

When I initialize vec, obviously I am allocating space for it separately. If I have no intention of using the data using array anymore, is it possible to somehow "move" the data pointed by array to the vector vec and not allocate any space for it separately?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...