How to convert vector to array
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];
Converting a vector to an array - Is there a 'standard' way to do this?
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.
C++ how to convert vector to an array?
You do not need (and should not) dereference - the function you call expects arrays, and you pass their first elements. Use
gsl_spline_init (spline, x_input_Array, y_input_Array, iNoOfPtsIni);
Fastest way to copy the contents of a vector into an array?
std::copy
, hands down. It’s heavily optimised to use the best available method internally. It’s thus completely on par with memcpy
. There is no reason ever to use memcpy
, even when copying between C-style arrays or memory buffers.
AS3: How to convert a Vector to an Array
your approach is the fastest ... if you think it's to verbose, then build a utility function ... :)
edit:
To build a utility function, you will probably have to drop the type as follows:
function toArray(iterable:*):Array {
var ret:Array = [];
for each (var elem:Foo in iterable) ret.push(elem);
return ret;
}
How to convert vector to array and access it
To begin with, you should understand how std::vector works: it is a self-expanding array, it can reallocate its internal storage whenever it needs.
A right way to get a pointer to internal array is to call std::vector::data member (available only in C++11):
double * a = v.data();
Note that this pointer is valid only until you modify the vector.
Just in case, "convert" here doesn't mean real conversion, the vector isn't modified and no new arrays are created. Only a pointer to the data stored in std::vector is received.
Related Topics
Initializer_List and Move Semantics
Which Is Faster: Stack Allocation or Heap Allocation
Convert Python Program to C/C++ Code
How to Have Functions Inside Functions in C++
Why Does Cout Print Char Arrays Differently from Other Arrays
Defining Static Members in C++
Are Inline Virtual Functions Really a Non-Sense
How to Determine the Version of the C++ Standard Used by the Compiler
Combining C++ and C - How Does #Ifdef _Cplusplus Work
What Is the Correct Way of Using C++11'S Range-Based For
How to Remove Unused C/C++ Symbols With Gcc and Ld
Is the Pimpl Idiom Really Used in Practice
C++ Static Initialization Order