Get array from .begin() and .end() iterators

I'm trying to get the array "inside" an std::vector.

I don't know C++ that well so basically I'm looking for a snippet to get the array (which is the pointer to the first element, iirc) and the size. I need this, because I want to transfer the content of the array to an accelerator device via OpenACC.

All I get from the function I'm supposed to manipulate, are two RA-Iterators for the beginning and the end of the data.

I know that not all of those have to be contiguous but the code I'll produce will be purely academical, so that should not be an issue for now.

Upvotes: 1

Views: 2285

Answers (3)

Jossie Calderon
Jossie Calderon

Reputation: 1415

myArray[myvector.end() - myvector.begin()]
for (std::vector<int>::iterator it = myvector.begin(), int i = 0; it!=myvector.end(); ++it, ++i)
        myArray[i] = myvector[i]// or whatever you want

This is how you use the iterators; make sure to use a loop because you have the beginning condition and the end condition.

Upvotes: 0

dirkster
dirkster

Reputation: 522

A std::vector is guaranteed to be contiguous in memory, so that shouldn't be an issue. You can get the address of (read: pointer to) the first element with

&*a.begin()

or more easily with

&a.first()

To get the size from .begin() and .end(), use

a.end() - a.begin()

Upvotes: 4

Dutow
Dutow

Reputation: 5668

If you want the entire vector, vector.data() is your friend.

If you need only a part of it:

std::vector<X>::iterator it1 = ... , it2 = ...;
X* item = &(*it1);
int elements = it2 - it1;

Upvotes: 2

Related Questions