c++vectorlanguage-lawyerstdvalarray

Why are std::vector and std::valarray initializing constructors different?


I have just been burned by the following.

If I want to initialize a std::vector of n elements with a constant X I do this:

std::vector<double> v(n, X);

But if I need to initialize a std::valarray of n elements with a constant X I need to swap the size and initializing constant:

std::valarray<double> va(X, n);

This seems to me like an arbitrary 'gotcha'.

Is there a technical reason or some design rationale provided by the standards committee when deciding about the order of the fill constructor's parameters when std::vector and std::valarray were standardized?


Solution

  • Because they don't come from the same place: vector comes from the STL library, and valarray doesn't (I haven't been able to find out where it comes from, but there seem to be strong connections to Fortran).

    Quoting Bjarne himself:

    Most of the time, work on each of these components progressed in isolation from work on the others. There was no overall design or design philosophy.
    [...]
    Basically, the committee failed to contain “design by committee” so whereas the STL reflects a clear philosophy and coherent style, most of the other components suffered. Each represents its own style and philosophy, and some (such as string) manage simultaneously to present several.

    (From "Evolving a language in and for the real world: C++ 1991-2006".)

    So I would say that the rationale is the traditional C++ one, "things are the way they are, and changing them for the sake of Standardization would break a lot of things, so let's leave well enough alone".