简体   繁体   English

如何在不分配更多存储空间的情况下从数组初始化向量?

[英]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. 在这里,我从一个函数获取数组,该函数分配内存中的空间并通过引用设置sizeArr {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. {开始编辑}不幸的是,该函数不是我编写的,我需要处理C样式数组,然后以某种方式将其转换为向量。 (If possible efficiently). (如果可能有效的话)。 {end edit} {结束编辑}

When I initialize vec , obviously I am allocating space for it separately. 当我初始化vec ,显然我正在为其单独分配空间。 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? 如果我不再打算使用array使用数据,是否可以以某种方式将array指向的数据“移动”到向量vec而不为它单独分配任何空间?

If the caller doesn't own the data (ie 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. 它具有std::vector的许多功能,但不拥有基础数据,并且不支持会导致调整大小或重新分配的操作。

Why do you even allocate the memory with a pointer for int? 为什么还要用int指针分配内存? There is a very high chance, that you have no reason for doing this. 您很有可能没有理由这样做。

If you have a compiler which assists c++11 it should be possible to just initialize the vector with std::vector vec{array}; 如果您有协助c ++ 11的编译器,则应该可以使用std :: vector vec {array};初始化向量。 Or if you dont need the array anymore, just delete it and push references of the array to the vector 或者,如果您不再需要该数组,则将其删除并将该数组的引用推到向量上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM