1

I tried googling for an answer but I was wondering if it is possible to construct a std::vector<T> from a T* pointer?

I looked at the API docs and it looks like it's not possible from the given constructors and the C++11 data() is for the container's allocation.

I am asking as I have a memory mapped file that returns a int* and it would be great to re-use a class that extensively uses std::vector<T>

I am looking for something like this:

const size_t n = ...
int* map = mmap(....);
std::vector<int> vec(map, n);
pezpezpez
  • 654
  • 8
  • 15
  • 1
    Do you mean making a copy, or reusing an existing buffer? – Pavel Minaev Jan 03 '15 at 15:01
  • 2
    `std::vector vec(map, map + n);` will instantiate a vector with the first `n` ints pointed at by `map`. – juanchopanza Jan 03 '15 at 15:01
  • @PavelMinaev I have already allocated memory from the mmap() function so I want it to reuse this allocation rather than the container creating an internal allocation. – pezpezpez Jan 03 '15 at 15:04
  • See also http://stackoverflow.com/questions/26346688/how-to-initialize-vector-from-array-without-allocating-more-storage-space – juanchopanza Jan 03 '15 at 15:29

1 Answers1

3

std::vector is all about managing it's buffers. As items are pushed into the container it may delete and reallocate new buffer. It wouldn't make sense for std::vector to take control of an existing vector as it may end up trying to delete and reallocate.

If you want you can write a custom allocator for your vector that uses mmap, but you can't make a vector take control of an existing buffer.

If you take away the requirements of memory management, the interface for vector is pretty simple and it wouldn't take much to write a compatible wrapper around your mmap'ed buffer.

Jay Miller
  • 2,184
  • 12
  • 11