How can we move the other way around?
If you know the valarray
's size at compile time, then you can prepare an int[3]
and copy the values to the individual elements, e.g. using std::copy
:
#include <valarray>
#include <algorithm>
#include <iostream>
int main()
{
std::valarray<int> va { 1, 2, 3 };
int arr[3] = { 0 };
std::copy(begin(va), end(va), arr);
std::cout << arr[0] << '\n';
std::cout << arr[1] << '\n';
std::cout << arr[2] << '\n';
}
You could even initialise the array with the correct values right away:
#include <valarray>
#include <iostream>
int main()
{
std::valarray<int> va { 1, 2, 3 };
int arr[] = { va[0], va[1], va[2] };
std::cout << arr[0] << '\n';
std::cout << arr[1] << '\n';
std::cout << arr[2] << '\n';
}
If the size isn't known at compile time, then use std::vector
instead:
#include <valarray>
#include <vector>
#include <iostream>
int main()
{
std::valarray<int> va { 1, 2, 3 };
std::vector<int> v(begin(va), end(va));
for (auto const& element : v)
{
std::cout << element << '\n';
}
}