vectors and arrays

D

Dave Rahardja

Is there a way to easily convert between a std::vector and a C-style array?

In the Microsoft C++/Dinkumware library, std::vector::begin() returns a
pointer to the data type and not some custom iterator for all types except
bool. This pointer can then be used as the base pointer to the array.

I don't think this is standard behavior, and I believe the cast is strictly
incorrect according to the STL standard. Am I right, or can I expect certain
types such as std::vector<int> to be cast-able to an array?

-dr
 
R

red floyd

Dave said:
Is there a way to easily convert between a std::vector and a C-style array?

In the Microsoft C++/Dinkumware library, std::vector::begin() returns a
pointer to the data type and not some custom iterator for all types except
bool. This pointer can then be used as the base pointer to the array.

I don't think this is standard behavior, and I believe the cast is strictly
incorrect according to the STL standard. Am I right, or can I expect certain
types such as std::vector<int> to be cast-able to an array?

-dr


assuming you have a prototype:

void f(T*, int nElems);

and a vector:

vector<T> v;

Then you can call:

f(&v[0],v.size());
 
I

Ivan Vecerina

Dave Rahardja said:
Is there a way to easily convert between a std::vector and a C-style
array?
The elements of a vector are required to be stored contiguously,
and may therefore be accessed as an array.
For a **non-empty** vector v, a pointer to the first element can
be obtained with &v.front() , or &v[0] . or &*v.begin() .
NB: if v is empty, each of the above expressions will trigger
undefined behavior, so make sure to check for this case.
In the Microsoft C++/Dinkumware library, std::vector::begin() returns a
pointer to the data type and not some custom iterator for all types except
bool. This pointer can then be used as the base pointer to the array.
This is an allowed behavior, but you cannot rely on it portably.
I don't think this is standard behavior, and I believe the cast is
strictly
incorrect according to the STL standard. Am I right, or can I expect
certain
types such as std::vector<int> to be cast-able to an array?
Equivalence of iterator and pointer is not portable.
Contiguous storage (and accessibility as a C array) is guaranteed.

hth-Ivan
 
D

Dave Rahardja

Equivalence of iterator and pointer is not portable.
Contiguous storage (and accessibility as a C array) is guaranteed.

I did not know that about contiguous storage. Thank you.

-dr
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,227
Latest member
Daniella65

Latest Threads

Top