By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,665 Members | 1,258 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,665 IT Pros & Developers. It's quick & easy.

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

P: n/a
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
Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
* ll***@hotmail.com (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.

Jul 22 '05 #2

P: n/a
On 26 Feb 2004 13:13:55 -0800, ll***@hotmail.com (lf) wrote:
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
le**@bdsoft.com
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
Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.