假设我有一个函数:
void someFunc(int *x,int count);
这是我无法控制的,所以我不能写它来接受迭代器。
这样称呼是否安全(不管具体的STL实现如何):
vector<int> v;
/* ... */
someFunc(&v[0],v.size());
很明显,一个反例是vector<bool>
.其他类型呢? (假设我没有以任何方式专门化 vector
)。
最佳答案
从标准的第 23.2.4 节第 1 点开始:
[...] The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
所以是的,它是安全的。
注意:如果 v
为空 v[0]
是未定义的行为,因此只有在 v
不为空。
关于c++ - 将 vector 作为数组传递是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3093451/