78. Use vector
(and string::c_str
) to exchange data with non-C++ APIs
Summary
vector
isn’t lost in translation: vector
and string::c_str
are your gateway to communicate with non-C++ APIs. But don’t assume iterators are pointers; to get the address of the element referred to by a vector<T>::iterator iter
, use &*iter
.
Discussion
vector
(primarily) and string::c_str
and string::data
(secondarily) are the best way to communicate data with non-C++ APIs in general, and C libraries in particular.
vector
’s storage is always contiguous, so accessing the address of its first element returns a pointer to its contents. Use &*v.begin()
, &v[0]
, or &v.front()
to get a pointer to v
’s first element. To get a pointer to a vector
’s n
-th element, prefer to do ...
Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.