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.
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.
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.:)
#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.