How do I convert a std::vector into std::array

I always store object sequences in vectors for the obvious benefits they bring, but am now in a situation where I frequently need to access data as arrays (I'm using C++ AMP). Anyway, so I was wondering if it is possible to create an std::array from an std::vector without copying the data? If so, how?

I would like to avoid using array_view but this would be my next option.
closed account (zb0S216C)
The last time I checked, "std::array" relied on a template parameter to determine the array's length. Since template parameters are evaluated at compile-time, relying on the size of a "vector" isn't going to work.

The "std::vector" overloads the sub-script operator so that it can mimic the syntax of an array access.

Wazzak
Last edited on
First of all take into account that the template non-type parameter of class std::array shall be a constant expression.

You can store in the array iterators of the vector. If you are not going to change values of the vector through the array then you can use simply vector's member function data.

I am sorry. You may even change the original data of the array using member function data.:)
Last edited on
Thanks vlad; how would this work? I can't find a "constructor" for std::array so how can I create such an array from a vector?
std::array has no explicitly defined constructor. It is an aggregate type. You can use standard algorithms to fill an array.

Consider the following example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>
#include <array>
#include <numeric>
#include <iterator>

int main()
{
	const std::vector<int>::size_type N = 12;
	std::vector<int> v( N );

	std::iota( v.begin(), v.end(), 1 );

	for ( std::vector<int>::size_type i = 0; i < v.size(); i += N / 3 )
	{
		std::array<std::vector<int>::iterator, N / 3> a;

		std::iota( a.begin(), a.end(), std::next( v.begin(), i ) );

		for ( auto x : a ) std::cout << *x << ' ';
// MS VC++	for each ( auto x in a ) std::cout << *x << ' ';
		std::cout << std::endl;
	}

	std::cout << std::endl;
}
 


If I did not make a typo the code must be compiled.
This only works if N is known at compile time, correct?

If I don't know N at compile time, will I have to use an array_view into the vector object?
Yes template non-type parameter as I said early shall be a const expression.
As for array_view I do not know what it is.
Ok thanks for that.
Topic archived. No new replies allowed.