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().