How do I convert a std::vector<double>
to a double array[]
?
-
9Kinda begs the question of why? You can access a vector as an array. What does an array do that a vector does not? – Michael Dorgan May 27 '10 at 17:17
-
147@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 – Michael Mrozek May 27 '10 at 17:20
-
8The 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 May 27 '10 at 17:21
-
@MichaelDorgan incredibly, sometimes is necessary. For example when passing as argument to a CUDA kernel – KansaiRobot Jun 11 '21 at 10:37
-
Zombie comment from 11 years ago - I love it :) – Michael Dorgan Jun 11 '21 at 18:10
-
2This functionality is particularly useful for vectors to `char*` when you have to build an argc/argv array and filter some options first. – Zenul_Abidin Jul 06 '21 at 00:12
10 Answers
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];

- 169,610
- 28
- 168
- 175
-
I tried this method. but all elements in the vector didn't copy to array. How to copy all the elements to the array? – ganuke May 27 '10 at 17:21
-
52@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](http://stackoverflow.com/questions/2923272/how-to-convert-vector-to-array-c/2923295#2923295) explains how – Michael Mrozek May 27 '10 at 17:22
-
4@ganuke: What is "the array"? You need to provide more information. What's the big picture? – GManNickG May 27 '10 at 17:22
-
void GMap::train( double* inputVector); this is the function I need to call. But I have a vector of double. so I need to copy that vector to a array. – ganuke May 27 '10 at 17:33
-
6@ganuke You don't, you just need a `double*` that points to the same data. This answer works for exactly that case – Michael Mrozek May 27 '10 at 17:36
-
oops.. is that so.. Then its ok. I'm new to C++ programing. thanks for helping me. – ganuke May 27 '10 at 17:41
-
@chris: There's two sorts of raw 2D arrays, and when you add `std::vector` and `std::array` into the mix, there's lots of combinations. For some sorts: yes. For most: no. – Mooing Duck Jun 18 '12 at 16:52
-
got an error: error C2440: 'initializing' : cannot convert from 'cv::Vector<_Tp> (*)[3]' to 'short *' – john k Dec 20 '12 at 01:45
-
Writing to an array vs. writing to vector sped up calculations 4 times in the debug mode. And this was a simple vector
v. As for reading operations speed increase was about x 2. So don't dismiss arrays. After all OpenCV uses both forms and I suspect not only due to comnpatability but also for efficiency reasons. – Vlad Jul 20 '13 at 01:16 -
2Since this line does not copy data, does that mean I don't need to delete a after I'm done with it? – guneykayim May 30 '14 at 08:49
-
6
-
1Is it guaranteed that &v[0] points to continuous range of memory? I'm getting memory corruption with semi-long vectors... – Denis V Nov 13 '14 at 14:42
-
4@DenisV Yes, as long as it's not a vector of `bools`; they're special-cased for space efficiency. It's one of the first things mentioned in the spec (23.2.4 Class template `vector`): "The elements of a vector are stored contiguously, meaning that if `v` is a `vector
` where `T` is some type other than `bool`, then it obeys the identity `&v[n] == &v[0] + n` for all `0 <= n < v.size()`." – Michael Mrozek Nov 13 '14 at 15:14 -
53
-
2@ThatPixelCherry it doesn't work for bool because vector
is implemented using a bitmap. – Giuseppe Pes Apr 09 '16 at 08:32 -
@MichaelMrozek : This is an incorrect answer. Suppose u initialize a vector in foo() which is in a.cpp and and call it from b.cpp the vector is cleared after it is out of scope u will be trying to use memory u shouldn't in b.cpp. So even though this is a short nice trick in O(1). This non copying trick may not work in a lot of scenarios! – Prakhar Agrawal Jul 14 '16 at 12:18
-
2The vector.data() answer (http://stackoverflow.com/a/40031309/564626) is better for C++11 – jfritz42 Feb 22 '17 at 03:52
-
@Vlad "this was a simple vector
v" -- vector – Jim Balter Aug 24 '17 at 03:46isn't "simple", it's bit-packed, so your efficiency factors are completely wrong. -
2
-
Is it possible that vector decides to reallocate its internal array due to memory management? If that happens the pointer will become invalid? – Spidey Jun 29 '18 at 10:15
-
2using &v[0] is undefined behavior if the std::vector or std::array is empty,if using c++0x better to use v.data().https://isocpp.org/wiki/faq/containers#vector-is-contiguous – Rahul_cs12 Jul 19 '18 at 07:46
-
The link in the anwer points to the whole general doc. Perhaps a link to where this was guaranteed would be useful – KansaiRobot Jun 11 '21 at 10:39
-
@KansaiRobot The link actually does point to the right issue, but the page is ridiculously long and most browsers won't jump down to the section until the page is fully loaded. It's issue #69 – Michael Mrozek Jun 11 '21 at 17:36
-
Great answer but for some reason, it doesn't work inside functions, i.e. if the vector and the array are the arguments of some function. – tomtom1-4 Mar 13 '22 at 09:46
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 double
s. 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.

- 494,350
- 52
- 494
- 543
-
22Note: use v.size() to get the number of elements for the new array: double arr[v.size()]; – rbaleksandar Dec 25 '13 at 21:09
-
11
-
@GManNickG : It works but I think there is some misunderstanding here. Imagine the following: you have a class with a bunch of pointers of various types that have to point to arrays, which are not known at the time you define your class and which are later on created by flushing various vectors and using their size-parameter to determine how much space is to be used. Another example: a simple function void arrayTest(unsigned int arrSize), that creates an array (short arr[arrSize];) in it by using its function-parameter for the size. – rbaleksandar Dec 26 '13 at 11:40
-
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: http://stackoverflow.com/a/17318040/87234. But as of now, it's simply not a standard option. – GManNickG Dec 26 '13 at 12:54
-
2Note: 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 May 14 '15 at 22:57
-
-
@GManNickG, This post states "double arr[100];" where 100 is fixed size, so using "new double[v.size];" will make it more flexible as it will not have limit of 100 – Jet May 16 '15 at 20:42
-
@Jet: you should use `std::vector
` in place of `new T[]`, don't do manual memory management. – GManNickG May 17 '15 at 06:38 -
3@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 May 28 '15 at 13:30
-
-
@convert Not necessarily. Many times `std::copy` becomes `memmove` or `memcpy`, and `std::copy` is more generic for people who are using this answer with something you cannot memcpy. – GManNickG Feb 20 '22 at 17:58
-
@GManNickG Agree, but since it´s about double, memcpy would be a more performat solution, or am I wrong? And std::copy from performance point of view beter then just a simple for loop? – convert Feb 20 '22 at 22:43
-
@convert It's highly dependent on context and if the compiler can deduce a `memcpy` vs [`memmove` call](https://godbolt.org/z/Wdf585jTE). Again, `std::copy` is simpler and always works - if profiling results say this needs to be a memcpy then go for it. See https://stackoverflow.com/a/13131253/87234 for example. – GManNickG Feb 21 '22 at 04:20
-
@GManNickG https://en.cppreference.com/w/cpp/string/byte/memcpy says it´s the fastest way to copy, that´s why I mentioned it. – convert Feb 21 '22 at 10:27
For C++11, vector.data()
will do the trick.
-
1Note: It doesn't copy the data of vector, it only stores pointer that points to the actual array the vector is using internally. – Rajan Feb 17 '22 at 14:05
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.

- 26,308
- 17
- 56
- 95

- 5,469
- 1
- 31
- 42
-
4...and make sure the vector isn't `empty()`, otherwise this would invoke the dreaded UB. – sbi May 27 '10 at 18:39
-
4
As to std::vector<int> vec
, vec to get int*
, you can use two method:
int* arr = &vec[0];
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)
}

- 5,931
- 3
- 49
- 56
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.
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;
}

- 3,588
- 2
- 39
- 40
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.
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
- 2