'C++ STL vector for existing data
Can I create an std::vector
using my pre-existing data instead of it allocating new memory and copying the data?
To be clearer, if I have a memory area (either a c-array or part of another vector or whatever) and I want to provide vector-like access to it, can I create a vector and tell it to use this block of memory?
Solution 1:[1]
No, but you could write your own class that does this. Since this would be a fairly common need I wouldn't be surprised if someone else has done this already.
However the normal C++ way would be to write template code to operate on iterators. You can create iterators for any portion of a vector, or for any portion of a C array (and much else). So writing template code for iterators is probably what you should be doing.
Solution 2:[2]
Since you can use a custom allocator when creating a vector
, it is technically possible.
However, I wouldn't recommend it. I'd just create a vector with a fixed size (apparently you can get a hold of that) and then use std::copy
.
Solution 3:[3]
Algorithms which iterate over a container accept a pair of iterators which define the input range. You can use the algorithm with iterators which point to a middle of a big container.
Examples:
std::vector<int> big_vector(100000);
// initialize it
//...
std::sort(big_vector.begin()+100, big_vector.begin()+200); // sort a subrange
int big_array[100000]; //c-style array
// initialize it
//...
std::sort(std::begin(big_array)+300, std::begin(big_array)+400); // sort a subrange
Solution 4:[4]
From C++20 we have std::span
which provides the exact same thing you are looking for. Take a look at https://en.cppreference.com/w/cpp/container/span.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | john |
Solution 2 | Luchian Grigore |
Solution 3 | Andrey |
Solution 4 | vpshastry |