将向量转换为数组 - 是否有"标准"方法来执行此操作?

11 c++ vector

我知道你可以这样做&theVector[0],但这是标准吗?这种行为总是得到保证吗?

如果没有,是否有更好的,更少"hackish"的方式来做到这一点?

Mys*_*ial 20

是的,这种行为是有保障的.虽然我不能引用它,但标准保证向量元素连续存储在内存中以允许这种情况.

但有一个例外:

vector<bool>由于模板专业化,它不起作用.

http://en.wikipedia.org/wiki/Sequence_container_%28C%2B%2B%29#Specialization_for_bool

此专门化尝试通过bools在位字段中打包来节省内存.但是,它打破了一些语义,因此,&theVector[0]一个vector<bool>不会起作用.

在任何情况下,vector<bool>被广泛认为是一个错误,所以替代是使用std::deque<bool>.

  • 只是另一个随机评论:在C++ 2011中,std :: vector有data()成员返回指向第一个元素的指针.这也适用于空矢量 (2认同)

Mil*_*ams 13

C++ 11提供了返回a 的data()方法.这允许你这样做:std::vectorT*

#include <iostream>
#include <vector>

int main()
{
  std::vector<int> vector = {1,2,3,4,5};
  int* array = vector.data();
  std::cout << array[4] << std::endl; //Prints '5'
}
Run Code Online (Sandbox Code Playgroud)

但是,执行此操作(或上述任何方法)可能很危险,因为如果向量调整大小,指针可能会变为无效.这可以显示为:

#include <iostream>
#include <vector>

int main()
{
  std::vector<int> vector = {1,2,3,4,5};
  int* array = vector.data();

  vector.resize(100); //This will reserve more memory and move the internal array

  //This _may_ end up taking the place of the old array      
  std::vector<int> other = {6,7,8,9,10}; 

  std::cout << array[4] << std::endl; //_May_ now print '10'
}
Run Code Online (Sandbox Code Playgroud)

这可能会崩溃或做任何事情所以要小心使用它.