Converting a vector to an array - Is there a '

2019-02-16 14:05发布

问题:

I know you can just do: &theVector[0], but is this standard? Is this behavior always guaranteed?

If not, is there a better, less 'hackish' way to do this?

回答1:

Yes, that behavior is guaranteed. Although I can't quote it, the standard guarantees that vector elements are stored consecutively in memory to allow this.

There is one exception though:

It will not work for vector<bool> because of a template specialization.

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

This specialization attempts to save memory by packing bools together in a bit-field. However, it breaks some semantics and as such, &theVector[0] on a vector<bool> will not work.

In any case, vector<bool> is widely considered to be a mistake so the alternative is to use std::deque<bool> instead.



回答2:

C++11 provides the data() method on std::vector which returns a T*. This allows you to do:

#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'
}

However, doing this (or any of the methods mentioned above) can be dangerous as the pointer could become invalid if the vector is resized. This can be shown with:

#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'
}

This could could crash or do just about anything so be careful using this.



回答3:

We can do this using data() method. C++11 provides this method. It returns a pointer to the first element in the vector. vector Even if it is empty, we can call this function itself without problems

  vector<int>v;
  int *arr = v.data();


回答4:

A less 'hackish' way? Well you could simply copy :

#include <iostream>
#include <vector>
using namespace std;



int main()
{ 
    vector<int> vect0r;
    int array[100];

    //Fill vector
    for(int i = 0; i < 10 ; i++) vect0r.push_back( i ) ;

    //Copy vector to array[ ]
    for(  i = 0; i < vect0r.size(); i++) array[i] = vect0r[i];

    //Dispay array[ ]
    for(  i = 0; i < vect0r.size(); i++)  cout<< array[i] <<" \n";

    cout<<" \n";

return 0;
}

More here : How to convert vector to array in C++



标签: c++ vector