c++ - 将 vector 作为数组传递是否安全?

标签 c++ arrays stl vector

假设我有一个函数:

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/

相关文章:

c++ - GetTimeZoneInformation 在 ubuntu 中等效?

c++ - C++ Anagram Solver速度优化

c++ - 如何访问第二个 map 迭代器?

javascript - 在多维数组中获取 Promise 的结果

javascript - 是否可以通过解构从数组创建对象?

c++ - std::array 与用于连续内存的 C 样式数组

c++ - 是否 libc+ +'s implementation of ` std::make_heap` 不一致

c++ - 在 C++ 代码中查找悬空的 else

c++ - 放置运算符函数的一致性

php - 如何在 PHP 中迭代 Dropbox 结果数组