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

A direct way to initialize a vector from an array is as follows:

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

Here I get an array from a function that allocates space in memory and sets sizeArr by reference. {start edit} Unfortunately, the function is not written by me, and I need to deal with an array of C styles, and then somehow convert it to a vector. (If possible, effective). {end edit}

When I initialize vec , I obviously allocate space for it separately. If I no longer intend to use the data with array , is it possible to somehow "move" the data indicated by the array symbol to the vec vector and not allocate any space for it separately?

+2
c ++ arrays vector
source share
2 answers

If the caller does not own the data (i.e. is not responsible for deleting it), then the simplest option would be to write a container-like shell:

 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); 

It has many functions of std::vector , but it does not own the underlying data and does not support any operations that can lead to resizing or redistribution.

+4
source share

Why do you even allocate memory with an int pointer? There is a very high probability that you have no reason for this.

If you have a compiler that helps C ++ 11, you can simply initialize the vector with std :: vector vec {array}; Or, if you no longer need an array, just delete it and click the array links to the vector

0
source share

All Articles