The function requires a pointer to an array const int* as a parameter. It is required to transfer a vector v<int> .
Are the following transfers equivalent: &v[0] and v.begin() ?
v.begin() returns an iterator, this is not a const int* .&*v.begin() , &v[0] and v.data() are equivalent.
Using v.data() preferable because it conveys better intent.
implementation-defined , so formally it can be a regular pointer. - 伪位蔚蠂慰位蠀蟿std::basic_string &v[0] you can also call on an empty container. The main thing is not to write there. - 伪位蔚蠂慰位蠀蟿begin() says that it returns an iterator to the first element, but there is no first element in the empty string. It seems to me, although it is not explicitly written, such behavior is not allowed, although it will work almost everywhere, at the expense of SSO. - ixSciNo, they are not equivalent, since v.begin() returns an iterator (ie, std::vector<int>::iterator ) to the first element of the vector<int> , and &v[0] pointer to the address in memory where the element from the vector is located ( Ie int* ).
Accordingly, the interface for working with such types is different, but, again, no one forbids dereferencing an iterator (but first you should check whether the iterator points to v.end() and then take the address of the received element.
And since vector emulates the operation of a standard C array (for example, fast random access to elements), all elements in it are placed in a general ensemble (that is, they are located in a row in memory), so the transfer method &v[0] will suit you, and moving on array elements through operator ++ applied to a function parameter, for example.
But in this case, you should think in advance exactly how you will take into account the array boundaries:
An example implementation through the 1st paragraph:
#include <vector> void func(const int* parm, const int elemsCount) { for (int itemNumber = 0; itemNumber < elemsCount; ++itemNumber, ++parm) { // ToDo: 写械泄褌褋胁懈褟 褋 *parm } } int main() { std::vector<int> v = {1, 2, 3, 4, 5}; func(&v[0], v.size()); } Source: https://ru.stackoverflow.com/questions/508501/
All Articles
cfor example. Or there is already a working interface. Andstd::vectorpretty easy to make friends with the native pointer where necessary. - 伪位蔚蠂慰位蠀蟿const int*. You cannot rewrite this function, or anything at all in this library. - 伪位蔚蠂慰位蠀蟿