如何初始化未分配更多的存储空间,从阵列载体? [英] How to initialize vector from array without allocating more storage space?

查看:126
本文介绍了如何初始化未分配更多的存储空间,从阵列载体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的直接的方式从阵列初始化矢量似乎是:

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

在这里,我正在从由参考分配内存,并设置 sizeArr 的空间功能的阵列。 {开始编辑}不幸的是,该功能不是我写的,我需要处理使用C风格的数组,然后将其转换为载体莫名其妙。 (如果可能的话有效)。 {结束编辑}

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}

当我初始化 VEC ,显然我为它单独分配空间。如果我没有使用阵列再使用数据的意图,是否有可能以某种方式移动由阵列指向的数据的向量 VEC 而不是单独它分配任何空间?

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?

推荐答案

如果主叫方不拥有数据(即不负责删除它),那么最简单的选择可能是写一个容器类包装

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_;
};

然后

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.

这篇关于如何初始化未分配更多的存储空间,从阵列载体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆