How to convert vector to array

后端 未结 10 1559
野的像风
野的像风 2020-11-22 09:20

How do I convert a std::vector to a double array[]?

相关标签:
10条回答
  • 2020-11-22 09:42

    As to std::vector<int> vec, vec to get int*, you can use two method:

    1. int* arr = &vec[0];

    2. int* arr = vec.data();

    If you want to convert any type T vector to T* array, just replace the above int to T.

    I will show you why does the above two works, for good understanding?

    std::vector is a dynamic array essentially.

    Main data member as below:

    template <class T, class Alloc = allocator<T>>
    class vector{
        public:
            typedef T          value_type;
            typedef T*         iterator;
            typedef T*         pointer;
            //.......
        private:
            pointer start_;
            pointer finish_;
            pointer end_of_storage_;
    
        public:
            vector():start_(0), finish_(0), end_of_storage_(0){}
        //......
    }
    

    The range (start_, end_of_storage_) is all the array memory the vector allocate;

    The range(start_, finish_) is all the array memory the vector used;

    The range(finish_, end_of_storage_) is the backup array memory.

    For example, as to a vector vec. which has {9, 9, 1, 2, 3, 4} is pointer may like the below.

    So &vec[0] = start_ (address.) (start_ is equivalent to int* array head)

    In c++11 the data() member function just return start_

    pointer data()
    { 
         return start_; //(equivalent to `value_type*`, array head)
    }
    
    0 讨论(0)
  • 2020-11-22 09:43

    We can do this using data() method. C++11 provides this method.

    Code Snippet

    #include<bits/stdc++.h>
    using namespace std;
    
    
    int main()
    {
      ios::sync_with_stdio(false);
    
      vector<int>v = {7, 8, 9, 10, 11};
      int *arr = v.data();
    
      for(int i=0; i<v.size(); i++)
      {
        cout<<arr[i]<<" ";
      }
    
      return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 09:44

    What for? You need to clarify: Do you need a pointer to the first element of an array, or an array?

    If you're calling an API function that expects the former, you can do do_something(&v[0], v.size()), where v is a vector of doubles. The elements of a vector are contiguous.

    Otherwise, you just have to copy each element:

    double arr[100];
    std::copy(v.begin(), v.end(), arr);
    

    Ensure not only thar arr is big enough, but that arr gets filled up, or you have uninitialized values.

    0 讨论(0)
  • 2020-11-22 09:46
    std::vector<double> vec;
    double* arr = vec.data();
    
    0 讨论(0)
提交回复
热议问题