如何在不分配更多存储空间的情况下从数组初始化向量? [英] How to initialize vector from array without allocating more storage space?

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

问题描述

从数组初始化向量的直接方法似乎是:

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 时,显然我是在为它单独分配空间.如果我不再打算使用 array 使用数据,是否有可能以某种方式将 array 指向的数据移动"到向量 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);

它具有 std::vector 的许多功能,但不拥有底层数据,并且不支持会导致调整大小或重新分配的操作.

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天全站免登陆