Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL vector for existing data

Tags:

c++

stl

vector

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?

like image 726
Baruch Avatar asked Oct 31 '12 09:10

Baruch


People also ask

How do you add a vector to a set?

Get the vector to be converted. Create an empty set, to store the result. Iterate through the vector one by one, and insert each element into the set. Print the resultant set.

How do you access vector data?

Access an element in vector using vector::at() reference at(size_type n); reference at(size_type n); It returns the reference of element at index n in vector. If index n is out of range i.e. greater then size of vector then it will throw out_of_range exception.

How do you assign a value to a vector?

The syntax for assigning values from an array or list: vectorname. assign(arr, arr + size) Parameters: arr - the array which is to be assigned to a vector size - number of elements from the beginning which has to be assigned.

How do you assign one vector to a v1 to v2?

Algorithm. Begin Initialize a vector v1 with its elements. Declare another vector v2. Call assign() to copy the elements of v1 to v2.


3 Answers

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.

like image 78
john Avatar answered Sep 23 '22 20:09

john


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.

like image 39
Luchian Grigore Avatar answered Sep 24 '22 20:09

Luchian Grigore


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
like image 43
Andrey Avatar answered Sep 22 '22 20:09

Andrey