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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…