c++ - 当需要数组时,将指针传递给 vector 中的第一个元素是否安全?

标签 c++ arrays stdvector

<分区>

Possible Duplicate:
Can I call functions that take an array/pointer argument using a std::vector instead?

我最近遇到了这样的事情:

class X {
    public: void foo(float* p, int elements);
};

= 需要一个浮点值数组的方法。

但在示例代码中,这是他们使用它的方式:

std::vector<float> bar;
bar.push_back(42);
// ...

X x;
x.foo( &bar[0], (int)bar.size() );

现在我想知道这是否是一种安全的方法,或者恰好适用于 std::vector 的大多数实现? (也许这是一个运算符重载的问题?我对这些东西还没有那么自信..)

最佳答案

是的,它很安全。

n3337 23.3.6.1/1。在 C++03 标准中,这是 23.2.4/1

A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. 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().

关于c++ - 当需要数组时,将指针传递给 vector 中的第一个元素是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12144246/

相关文章:

c++模板化为特定类型而不使用传统的模板特化

c++ - 如何在google code jam中输入c++代码的测试用例

javascript - MongoDB 返回未定义

c++ - 为什么编译超过100,000行的std::vector::push_back需要很长时间?

c++ - GUI系统架构?

javascript - 为什么我的innerHTML不返回数组对象?

c - 多维数组,不同方式表示grid[22][0]的地址

c++ - 根据一组模式对 vector 的成员重新排序

c++ - c++ 中 std::vector 的内存问题

c++ - 从 C++ 中的系统函数获取一个整数(大于 255)