3

Is it ok/safe/good practice to write the following in order to fill a valarray with the content of a vector?

vector<int> myVect = {2,0,1,0,0,1,1,0,0,0}; // Any vector
valarray<int> myVala ( &(myVect[0]), myVect.size() );
//Edit: as suggested by Xeo, this code looks much cleaner (C++11)
valarray<int> myVala ( myVect.data(), myVect.size() );

It seems to work fine but I would like to be sure it works on any case.

wxc3
  • 31
  • 1
  • 3
  • These days, I would question whether it is good practice to use `valarray` at all. It's the black sheep of the standard library. – Sebastian Redl Dec 02 '14 at 12:54
  • Why is that? I plan to use them for selection of subsets with masks and slices. I'm not familiar with this structure but it seems useful at first sight. – wxc3 Dec 02 '14 at 15:22
  • It just never got popular. Most implementations are actually poorly optimized, which defeats the point of using it. It's a bit of a chicken-and-egg situation. – Sebastian Redl Dec 02 '14 at 15:46

1 Answers1

3

Yes, this is perfectly fine. The contents of vector are guaranteed to be contiguous (see [vector.overview], §1 in C++ standard).

Note that since C++11, you can initialize valarray using initializer list directly.

jrok
  • 54,456
  • 9
  • 109
  • 141
  • 1
    A bit better would be (besides init-list, say if the data came from elsewhere): `std::valarray vla(vec.data(), vec.size())` – Xeo Dec 02 '14 at 12:59
  • This is indeed much more readable using .data(), I edited my message to include this notation. – wxc3 Dec 02 '14 at 15:43