476

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

7
  • 9
    Kinda begs the question of why? You can access a vector as an array. What does an array do that a vector does not? Commented May 27, 2010 at 17:17
  • 155
    @Michael The typical use case I have is using a vector in my own code and needing to call a third-party function that takes an array Commented May 27, 2010 at 17:20
  • 8
    The terminology being thrown around is confusing. A pointer isn't an array. Do we want a pointer to the first element of an array, or an array?
    – GManNickG
    Commented May 27, 2010 at 17:21
  • 2
    This functionality is particularly useful for vectors to char* when you have to build an argc/argv array and filter some options first. Commented Jul 6, 2021 at 0:12
  • 1
    @MichaelDorgan zombie comments never die. It's easier than trying to mix std::array with legacy code in some instances.
    – ObiDan
    Commented Mar 27 at 15:49

10 Answers 10

681

There's a fairly simple trick to do so, since the spec now guarantees vectors store their elements contiguously:

std::vector<double> v;
double* a = &v[0];
24
  • 55
    @ganuke You're not copying, you're making a pointer that points to the actual array the vector is using internally. If you want to copy GMan's answer explains how Commented May 27, 2010 at 17:22
  • 4
    @ganuke: What is "the array"? You need to provide more information. What's the big picture?
    – GManNickG
    Commented May 27, 2010 at 17:22
  • 7
    @ganuke You don't, you just need a double* that points to the same data. This answer works for exactly that case Commented May 27, 2010 at 17:36
  • 6
    @guneykayim The vector owns that memory, you shouldn't free it Commented May 30, 2014 at 14:35
  • 56
    std::vector<double> v; double* a = v.data(); Commented Nov 10, 2015 at 7:38
208

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.

14
  • 23
    Note: use v.size() to get the number of elements for the new array: double arr[v.size()]; Commented Dec 25, 2013 at 21:09
  • 12
    @rbaleksandar: Arrays can't have a non-constant expression size.
    – GManNickG
    Commented Dec 26, 2013 at 6:04
  • 3
    @rbaleksandar No misunderstanding; in C++11 and prior, array sizes must be integral constant expressions. Your function example is a common use for VLAs in C, but only supported by (nonstandard) extension in C++. It may come to C++14 though: stackoverflow.com/a/17318040/87234. But as of now, it's simply not a standard option.
    – GManNickG
    Commented Dec 26, 2013 at 12:54
  • 3
    Note: Use "malloc" or "new" to dynamically allocate memory with size v.size(), and then copy all there. And keep in mind to "free()" or "delete" the pointer when you don't need it anymore.
    – Jet
    Commented May 14, 2015 at 22:57
  • 4
    @GManNickG I think @Jet is saying that if you want to convert a vector to an array, and you intend to size the array using the size() function of the std:vector you'll need to use new or malloc to do that. As it was already pointed out (by you) that double arr[v.size()] is not valid. Using vector in place of new is a good idea, but the entire point of the question is how you can convert a vector into an array.
    – RyanP
    Commented May 28, 2015 at 13:30
171

For C++11, vector.data() will do the trick.

1
  • 2
    Note: It doesn't copy the data of vector, it only stores pointer that points to the actual array the vector is using internally.
    – Rajan
    Commented Feb 17, 2022 at 14:05
23
vector<double> thevector;
//...
double *thearray = &thevector[0];

This is guaranteed to work by the standard, however there are some caveats: in particular take care to only use thearray while thevector is in scope.

2
  • 4
    ...and make sure the vector isn't empty(), otherwise this would invoke the dreaded UB.
    – sbi
    Commented May 27, 2010 at 18:39
  • 4
    (undefined behavior) Commented Feb 7, 2021 at 12:39
23

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.

enter image description here

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)
}
15

Vectors effectively are arrays under the skin. If you have a function:

void f( double a[]);

you can call it like this:

vector <double> v;
v.push_back( 1.23 )
f( &v[0] );

You should not ever need to convert a vector into an actual array instance.

0
5
std::vector<double> vec;
double* arr = vec.data();
4

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;
}
1

If you have a function, then you probably need this:foo(&array[0], array.size());. If you managed to get into a situation where you need an array then you need to refactor, vectors are basically extended arrays, you should always use them.

-2

You can do some what like this

vector <int> id;
vector <double> v;

if(id.size() > 0)
{
    for(int i = 0; i < id.size(); i++)
    {
        for(int j = 0; j < id.size(); j++)
        {
            double x = v[i][j];
            cout << x << endl;
        }
    }
}
1
  • v [i][j]; for 2d array Commented Oct 30, 2017 at 20:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.