通过原始指针访问整数向量的元素

Accessing elements of a vector of ints by raw pointers

请问下面的代码是否合法

基本上我有一个 std::vector<int> 并且我有一个处理 int 数组的遗留函数。由于 std::vector 的元素始终是连续的,因此代码应该始终有效(它实际上适用于我的实现),但对我来说它似乎仍然有点 hack。

#include <vector>
#include <iostream>

void LecagyFunction(int *data, int length)
{
  for (int i = 0; i < length; i++)
    std::cout << data[i] << std::endl;
}

int main()
{
  std::vector<int> vector;
  vector.push_back(5);
  vector.push_back(4);
  vector.push_back(3);
  LecagyFunction(&vector[0], vector.size());
}

预期的输出是:

5
4
3

这不是 hack,而是 vector 的 100% 合法(和预期)使用。在 C++11 中,你的代码应该被重写以利用 data() 成员——它是为空向量定义的,不像 operator[].

LecagyFunction(vector.data(), vector.size());

附带说明一下,上述技术不适用于 vector<bool>,因为后者不遵循正则向量的属性(这是一个糟糕的想法,现在每个人都明白了)。

发件人:http://www.cplusplus.com/reference/vector/vector/

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

发件人:http://en.cppreference.com/w/cpp/container/vector

The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets on regular pointers to elements. This means that a pointer to an element of a vector may be passed to any function that expects a pointer to an element of an array.

所以是的,完全合法并且打算以这种方式工作。