# Blitz++ Class Reference: Vector<T>

### Sections Summary Synopsis Template parameter Public types Constructors Member functions Member operators Operators Global math functions Other global functions Example | ### Related topics and classes The Range class | ### Inheritance diagram MemoryBlockReference<T> | Vector<T>

## Synopsis

    #include <blitz/vector.h>
    using namespace blitz;
    Vector<double> x(100);

## Template parameter

The template parameter of Vector<T> is the element type of the vector. This should an integral, floating point, or complex type. These choices of T should work:

- bool, char, unsigned char, short int, short unsigned int, int, unsigned int, long, unsigned long
- float, double, long double
- complex<float>, complex<double>, and complex<long double>

Other types may work provided they have the necessary numeric semantics.

## Public types

Vector<T> declares several publicly accessible types. They may be accessed using the scope (::) operator: e.g.

    Vector<double> x(50);                       // Create a vector of length 50
    Vector<double>::T_iterator z = x.begin();   // Get an iterator for x

Type | Description
--- | ---
T_numtype | The numeric type of the vector elements (e.g. double)
T_vector | Complete type of the vector itself (e.g. Vector<double>)
T_iterator | STL-like iterator to be used on this vector (see begin(), end()) ** Not yet supported
T_constIterator | STL-like const iterator to be used on this vector (see begin(), end()) ** Not yet supported

## Constructors

- Vector()
  Default constructor. No memory is allocated; the length of the vector is zero. The vector may subsequently be resized using resize(), or used to refer to another vector's data using reference().
- Vector(size_t length)
  Create a new vector of the given length. Memory is allocated using new. Elements are not initialized.
- Vector(Vector<T_numtype>& x)
  Creates a reference (or alias) to the data of vector x. Both x and this vector now refer to the same underlying data, so any changes made to the data via x will be visible in this vector. (Note: T_numtype is a publicly declared typedef for the template parameter).
- Vector(Vector<T_numtype>& x, Range r)
  Creates a reference (or alias) to a portion of the data of vector x. The range object specifies an interval of the index set. For example,

      Vector<double> x(50);                // Create a vector of length 50
      Vector<double> y(x, Range(10,20));  // y is now of length 11, and
                                           // refers to elements 10-20 of x
      y[5] = 3;                            // y[5] is aliased to x[15]

- Vector(size_t length, T_numtype initValue)
  Creates a new vector of the given length, and initializes all elements to initValue. Memory is allocated using new.
- Vector(size_t length, T_numtype firstValue, T_numtype inc)
  Creates a new vector of the given length, and initializes the elements to [ firstValue, firstValue + inc, firstValue + 2 * inc, ..., firstValue + (length-1) * inc ]. Memory is allocated using new.
- Vector(Range r)
  Creates a vector and initializes the elements to the range r. For example,

      Vector<int> z(Range(0,5));    // z = [ 0, 1, 2, 3, 4, 5 ]

- Vector(size_t length, Random<P_distribution>& random)
  Creates a vector and initializes its elements with random numbers. For example,

      #include <blitz/rand-normal.h>
      Random<Normal> gaussianNoise(0.0, 2.5);     // Zero-mean, variance 2.5
      Vector<double> x(50, gaussianNoise);

- Vector(size_t length, T_numtype* [restrict] data, int stride = 1)
  Creates a vector which refers to the given data. The NCEG restrict keyword can be used only with compilers which support it. The stride parameter gives the spacing of elements: in the created vector, element i will be data[i * stride]. When the vector object is destroyed, the memory is not freed (i.e. the vector does not assume ownership of the data).
- Vector(vector expression)
  Creates a vector of appropriate length and stores the result of vector expression in it. (See the explanation of expression templates). Examples:

      // Create a vector of length 16 containing a sampled cosine (full period)
      Vector<double> x(cos(Range(0,15) * 2 * M_PI / 16.0));

      // Create a new vector containing an approximation of the derivative
      // of x.
      Range I(1,15);
      double delta = 1 / 16.;    // Spacing between samples
      Vector<double> y = (x(I) - x(I-1)) / delta;

## Member functions

- T_iterator begin() ** NOT YET SUPPORTED
  Returns an STL-compliant iterator positioned at the beginning of the vector's data. T_iterator is a public type declared by Vector<T_numtype>, and should be used to specify the type of the iterator:

      Vector<double> x(50);
      Vector<double>::T_iterator iter = x.begin();

  Since T_iterator is STL-compliant, it may be used with the standard template library routines. [GIVE EXAMPLES] See also end().
- T_constIterator begin() const ** NOT YET SUPPORTED
  Returns an STL-compliant const iterator positioned at the beginning of the vector's data. A const iterator has read-only access to the vector elements. T_constIterator is a public type declared by Vector<T_numtype>, and should be used to specify the type of the iterator:

      Vector<int> z(50,0,1);       // Creates the vector [ 0 1 2 ... 49 ]
      const Vector<int>& zref = z; // Create a const reference to z
      Vector<int>::T_constIterator iter = zref.begin();

  Since T_constIterator is STL-compliant, it may be used with the standard template library routines. [GIVE EXAMPLES] See also end().
  The begin() method is const-overloaded. By default, a non-const iterator is returned. A const iterator is returned only when the vector itself is const.
- T_vector copy() const
  Returns a copy of the vector. A new block of memory is allocated, and the vector copy is guaranteed to have unit stride.
- T_iterator end()
  Returns an STL-compliant iterator positioned at the end of the vector's data. See begin() above.
- T_constIterator end() const
  Returns an STL-compliant const iterator positioned at the end of the vector's data. See begin() above.
- T_numtype * [restrict] data()
  const T_numtype * [restrict] data() const
  Obtain a pointer to the beginning of the vector data. This method should be used with caution, since it has the potential to cause data corruption and/or segment violations if used improperly. The vector data is not necessarily stored contiguously; the spacing between vector elements can be obtained via the stride() member function. Here is an example:

      Vector<float> x(10,0,1);          // Creates [ 0 1 2 3 4 5 6 7 8 9 ]
      float* xptr = x.data();           // Get a pointer to the vector data
      int length = x.length();          // Obtain the length of the vector (10)
      int stride = x.stride();          // Note that stride may be negative

      for (int i=0; i < length; ++i)
          xptr[i * stride] = 7;         // Set each element to 7

      // Now the vector contains [ 7 7 7 7 7 7 7 7 7 7 ]
      // Note that "x = 7;" would accomplish the same result.

  The NCEG restrict keyword is applicable only if the compiler supports it.
  The data() method is const-overloaded: if the vector is const, then data() returns a const T_numtype* pointer.
- size_t length() const
  Returns the length of the vector.
- void makeUnique()
  If the vector's elements are referenced (or aliased) by another vector, a copy is made, and on return the vector refers to the new copy.
- void reference(T_vector& x)
  Makes the vector an alias for vector x. After this member function is used, both the vector and x refer to the same underlying data.
- void resize(size_t length)
  If length is different than the current length of the vector, the vector is resized. The current contents are lost.
- void resizeAndPreserve(size_t newLength)
  Allocates a new vector of size newLength, and copies as much of the current vector as will fit into the new vector. If the new vector is larger than the previous vector, then the unused elements are left uninitialized.
- Vector<T_numtype> reverse()
  Returns a view of the vector in reverse order. This is done using a negative stride.
- int stride() const
  Returns the distance between vector elements in memory. This will normally be 1 (referred to as unit stride).

## Member operators

    T_numtype        operator()(unsigned i) const
    T_numtype&       operator()(unsigned i)
    T_numtype        operator[](unsigned i) const
    T_numtype&       operator[](unsigned i)
    T_vector         operator()(Range r)
    T_vector         operator[](Range r)
    T_pick           operator[](Vector<int>)        ** Currently broken

### Iostream operators

    ostream& operator>>(ostream& os, const vector expression&);

Formats a vector or vector expression for output. In future releases, several output formats will be supported.

### Arithmetic operators

Arithmetic operators are implemented using expression templates. These assignment operators are supported:

    operator=(vector expression)
    operator+=(vector expression)
    operator-=(vector expression)
    operator*=(vector expression)
    operator/=(vector expression)
    operator%=(vector expression)
    operator^=(vector expression)
    operator&=(vector expression)
    operator|=(vector expression)
    operator>>=(vector expression)
    operator=(vector expression)

A vector expression can be any combination of these operators and operands, as well as use of the math functions listed later.

#### Vector expression operators

    + - * / % ^ & | >> <<
    > < >= <= == != && ||

#### Vector expression operands

- Vector<T_numtype>
- Vector<T_numtype2> (A vector of a different type)
- VectorPick<T_numtype>
- Range
- Random ** NOT YET FULLY SUPPORTED
- Scalar constants (int,float,double,long double)
- Complex constants (complex<float>, complex<double>, complex<long double>)

Arithmetic type promotion for vectors is identical to type promotion for built-in types. For example, adding a double constant to a Vector<int> will result in a Vector<double>; multiplying a Vector<long double> by a Vector<float> will result in a Vector<long double>. Generally, the result is promoted to which ever type preserves the greatest precision.

Note that division and multiplication of integers may result in truncation and/or wraparound, since the result remains an integer type. The solution is to cast the elements of one of the vectors as floating-point types; see cast<T2> below. ** the cast() function is not yet implemented

    Vector<int> x(5), y(5);
    Vector<double> z(5);

    // ...

    z = x / y;      // Calculated using integer math, then cast as double
                    // Results in truncation

    z = x / cast<double>(y);   // Calculated using floating point

### Single-operand math functions

##### Notes

- Single operand math functions are evaluated using expression templates.
- If used on an integer vector, most of the functions below will return the answer type as a double.

Function | Description | Real vectors | Complex vectors | Availability
--- | --- | --- | --- | ---
abs | Absolute value | Y | Y | all |
acos | Inverse cosine. Elements must be in the range [-1,+1]. The resulting elements lie in [-Pi,+Pi]. | Y | Y | all |
acosh | Inverse hyperbolic cosine | Y |  | all |
arg | Argument (phase/angle) of a complex vector. Result is a scalar vector whose elements lie in [-Pi, +Pi]. |  | Y | allb
asin | Inverse sine. Elements must be in the range [-1,+1]. The resulting elements lie in [-Pi,+Pi]. | Y | Y | all |
asinh | Inverse hyperbolic sine | Y |  | all |
atan | Inverse tangent. Resulting elements lie in [-Pi,+Pi]. | Y | Y | all |
atanh | Inverse hyperbolic tangent | Y |  | all |
cast<T2> | Cast vector elements to type T2 ** NOT YET AVAILABLE | Y | Y | somee
cbrt | Cubic root | Y |  | somed |
ceil | Smallest floating integer not less than element | Y |  | all |
class | Floating-point classification. Result is an integer vector with elements taking values FP_PLUS_NORM, FP_MINUS_NORM, FP_PLUS_ZERO, FP_MINUS_ZERO, FP_PLUS_INF, FP_MINUS_INF, FP_PLUS_DENORM, FP_MINUS_DENORM, FP_SNAN, FP_QNAN as defined in <float.h> | Y |  | somed |
conj | Complex conjugate |  | Y | allb
cos | Cosine. Resulting elements lie in [-1,+1]. | Y | Y | all |
cosh | Hyperbolic cosine | Y | Y | all |
exp | Exponential. | Y | Y | all |
expm1 | Exponential minus one: exp(x)-1 | Y |  | somec |
erf | Error function | Y |  | somec |
erfc | Complementary error function (1-erf(x)). | Y |  | somec |
fabs | Same as abs | Y |  | all |
finite | Nonzero if finite. Result is integer. | Y |  | somed |
floor | Largest floating int not greater than x | Y |  | all |
ilogb | Integer unbiased exponent | Y |  | somed |
imag | Imaginary portion of a complex vector. Result is a scalar vector which may be used as an lvalue. |  | Y | allb
isnan | Nonzero if x is NaNS (Signalling Not a Number) or NaNQ (Quiet Not A Number). Result is integer. | Y |  | somed |
itrunc | Truncate and convert to integer. Result is integer. | Y |  | somed |
inv | Inverse of a complex number |  | Y | allb
j0 | Bessel function first kind, order 0 | Y |  | somec |
j1 | Bessel function first kind, order 1 See also y0(x), y1(x), jn(x,y) and yn(x,y). | Y |  | somec |
lgamma | Log absolute gamma | Y |  | somec |
log | Natural logarithm | Y | Y | all |
logb | Unbiased exponent (IEEE) | Y |  | somec |
log1p | Natural logarithm of (1+x) | Y |  | somec |
log10 | Logarithm base 10 | Y | Y | all |
nearest | Nearest floating point integer to x. | Y |  | somed |
norm | Norm (magnitude) of a complex vector. Result is a scalar vector. |  | Y | allb
real | Real portion of a complex vector. Result is a scalar vector which may be used as an lvalue. |  | Y | allb
rint | Round to floating point integer, using the current floating-point rounding mode. Rounding mode is read and set by the functions fp_read_rnd() and fp_swap_rnd(). (See system man pages) | Y |  | somec |
rsqrt | Reciprocal square root (i.e. 1.0/sqrt(x)) | Y |  | somed |
sin | Sine. Resulting elements lie in [-1,+1]. | Y | Y | all |
sinh | Hyperbolic sine | Y | Y | all |
sqr | Square: equivalent to x*x | Y | Y | alle |
sqrt | Square root | Y | Y | all |
tan | Tangent | Y | Y | all |
tanh | Hyperbolic tangent | Y | Y | all |
trunc | Nearest floating-point integer in the direction of zero | Y |  | somec |
uitrunc | Truncate and convert to unsigned. Result is unsigned integer. | Y |  | somed
y0 | Bessel function 2nd kind, order 0 | Y |  | somec |
y1 | Bessel function 2nd kind, order 1 See also yn(x,y) below | Y |  | somec |

aANSI C math function
bANSI C++ math function
cIEEE 754 standard required function
dIEEE 754 recommended function
eNonstandard function specific to Blitz++

### Global math functions with two operands

** These functions are not yet implemented **

    All the two operand math functions are provided in three forms:

    atan2(double,vector)
    atan2(vector,double)
    atan2(vector,vector)
    copysign(vector,double)
    drem(d,d)
    fmod(d,d)
    frexp(d, Vector<int>& e)  NOT INCLUDED
    hypot(d,d)
    jn(int, d)                      NOT INCLUDED
    ldexp(d,i)                      NOT INCLUDED
    modf(d, Vector<int>& e)   NOT INCLUDED
    max(d, d)
    min(d, d)
    nextafter(d, d)
    polar(d,d)                      NOT INCLUDED
    pow(d,d)
    remainder(d,d)
    scalb(d,d)
    unordered(d,d)
    yn(int,d)                       NOT INCLUDED

## Other global functions

(These functions are available)

    accumulate

    dot
    delta

    max
    maxIndex
    maxValue
    mean
    min
    minIndex
    minValue
    norm

    reverse

    sum

## The where function

The where(X,Y,Z) function provides the same functionality as the operator X ? Y : Z. If X is logical true, then Y is returned; otherwise, Z is returned.

The where function is implemented using expression templates. The arguments X, Y, and Z can each be vectors, vector expressions, Range, or Vector picks.

## Example

Please see the files in the Blitz++/examples directory.