&vector[ 0 ] vs. &vector.front()

L

lf

If I want to get a pointer to the initial data element
in a vector<double>, does it make any difference whether
I use (for vector<double> v)
double* pVec1 = &v[0];
or
double* pVec2 = &v.front();

The intention is to pass the pointer to a function that
expects such type. I vaguely remember someone recommended
the second approach, but why?


--Leon
 
A

Alf P. Steinbach

* (e-mail address removed) (lf) schriebt:
If I want to get a pointer to the initial data element
in a vector<double>, does it make any difference whether
I use (for vector<double> v)
double* pVec1 = &v[0];
or
double* pVec2 = &v.front();

The intention is to pass the pointer to a function that
expects such type. I vaguely remember someone recommended
the second approach, but why?

There seems to be no difference.

Perhaps readability?

It would, however, make a difference if you wrote


double* pVec3 = &v.at( 0 );


since in this case you get an exception if there is no element #0.
 
L

Leor Zolman

If I want to get a pointer to the initial data element
in a vector<double>, does it make any difference whether
I use (for vector<double> v)
double* pVec1 = &v[0];
or
double* pVec2 = &v.front();

The intention is to pass the pointer to a function that
expects such type. I vaguely remember someone recommended
the second approach, but why?


--Leon

One reason I can think of to prefer the front() approach is that it will
work with std::list, while subscripting will not. That would only bite you
if you switched mid-stream from using a vector/deque to using a list,
however. But within a template, it would give you the added flexibility of
supporting lists.

I did notice something else that, although not likely to be an issue, still
/might/: front() has UB if the container has no elements (size() == 0).
While it would be just about as undefined to use a subscript of zero on a
0-length array, it seems that a zero-length array is far less likely to
happen by accident than a zero-length STL container (where you may simply
have erased everything, or never stuffed any values into it, etc...)
-leor


Leor Zolman
BD Software
(e-mail address removed)
www.bdsoft.com -- On-Site Training in C/C++, Java, Perl & Unix
C++ users: Download BD Software's free STL Error Message
Decryptor at www.bdsoft.com/tools/stlfilt.html
 

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

Members online

Forum statistics

Threads
474,163
Messages
2,570,897
Members
47,434
Latest member
TobiasLoan

Latest Threads

Top