Since C++was standardized in 1998,the C++elite haven¡¯tbeenterri-bly
subtle in their attempt to nudge programmers away from arrays
and towards vectors. They¡¯ve been similarly overt in trying to get devel-opers
to shift from char* pointers to string objects. There are good rea-sons
for making these changes, including the elimination of common
programming errors (see Item 13) and the ability to take full advan-tage
of the power of the STL algorithms (see, e.g., Item 31).
Still, obstacles remain, and one of the most common is the existence
of legacy C APIs that traffic in arrays and char* pointers instead of vec-tor
and string objects. Such APIs will exist for a long time, so we must
makepeace with them if we aretouse theSTL effectively.
Fortunately, it¡¯s easy. If you have a vector v and you need to get a
pointer to the data in v thatcan be viewedasan array,just use&v[0].
For a string s, the corresponding incantation is simply s.c_str().But
read on. As the fine print in advertising often points out, certain
restrictions apply.
Given
vector<int> v;
the expression v[0] yields a reference to the first element in the vector,
so &v[0] is a pointer to that first element. The elements in a vector are
constrained by the C++ Standard to be stored in contiguous memory,
just like an array, so if we wish to pass v to a C API that looks some-thing
like this,
void doSomething(const int* pInts, size_t numInts);
we can do it like this:
doSomething(&v[0], v.size());
Maybe. Probably. The only sticking point is if v is empty. If it is, v.si ze()
is zero, and &v[0] attempts to produce a pointer to something that
does not exist. Not good. Undefined results. A safer way t