当前位置: 首页 > 编程日记 > 正文

C++向量类模板(支持实数向量与复数向量的各种运算)

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

头文件:

/** Copyright (c) 2008-2011 Zhang Ming (M. Zhang), zmjerry@163.com** This program is free software; you can redistribute it and/or modify it* under the terms of the GNU General Public License as published by the* Free Software Foundation, either version 2 or any later version.** Redistribution and use in source and binary forms, with or without* modification, are permitted provided that the following conditions are met:** 1. Redistributions of source code must retain the above copyright notice,*    this list of conditions and the following disclaimer.** 2. Redistributions in binary form must reproduce the above copyright*    notice, this list of conditions and the following disclaimer in the*    documentation and/or other materials provided with the distribution.** This program is distributed in the hope that it will be useful, but WITHOUT* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for* more details. A copy of the GNU General Public License is available at:* http://www.fsf.org/licensing/licenses*//******************************************************************************                              usingdeclare.h** Usually used name declaration.** Zhang Ming, 2010-08, Xi'an Jiaotong University.*****************************************************************************/#ifndef USINGDECLARE_H
#define USINGDECLARE_Hnamespace splab
{using std::cin;using std::cout;using std::cerr;using std::endl;using std::string;using std::complex;using std::ostream;using std::istream;using std::min;using std::max;using std::swap;using std::ceil;using std::abs;using std::cos;using std::sin;using std::tan;using std::acos;using std::asin;using std::atan;using std::exp;using std::log;using std::log10;using std::sqrt;using std::pow;}
// namespace splab#endif
// USINGDECLARE_H
/** Copyright (c) 2008-2011 Zhang Ming (M. Zhang), zmjerry@163.com** This program is free software; you can redistribute it and/or modify it* under the terms of the GNU General Public License as published by the* Free Software Foundation, either version 2 or any later version.** Redistribution and use in source and binary forms, with or without* modification, are permitted provided that the following conditions are met:** 1. Redistributions of source code must retain the above copyright notice,*    this list of conditions and the following disclaimer.** 2. Redistributions in binary form must reproduce the above copyright*    notice, this list of conditions and the following disclaimer in the*    documentation and/or other materials provided with the distribution.** This program is distributed in the hope that it will be useful, but WITHOUT* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for* more details. A copy of the GNU General Public License is available at:* http://www.fsf.org/licensing/licenses*//******************************************************************************                                 constants.h** Some constants often used in numeric computing.** Zhang Ming, 2010-01, Xi'an Jiaotong University.*****************************************************************************/#ifndef	CONSTANTS_H
#define CONSTANTS_Hnamespace splab
{const double	EPS		    = 2.220446049250313e-016;const double	PI		    = 3.141592653589793;const double	TWOPI	    = 6.283185307179586;const double	HALFPI	    = 1.570796326794897;const double	D2R 	    = 0.017453292519943;const double	EXP		    = 2.718281828459046;const double	RT2		    = 1.414213562373095;const double	IRT2	    = 0.707106781186547;const int		FORWARD	    = 1;const int		INVERSE	    = 0;const int		MAXTERM	    = 20;const int       INITSIZE    = 20;const int       EXTFACTOR   = 2;}
// namespace splab#endif
// CONSTANTS_H
/** Copyright (c) 2008-2011 Zhang Ming (M. Zhang), zmjerry@163.com** This program is free software; you can redistribute it and/or modify it* under the terms of the GNU General Public License as published by the* Free Software Foundation, either version 2 or any later version.** Redistribution and use in source and binary forms, with or without* modification, are permitted provided that the following conditions are met:** 1. Redistributions of source code must retain the above copyright notice,*    this list of conditions and the following disclaimer.** 2. Redistributions in binary form must reproduce the above copyright*    notice, this list of conditions and the following disclaimer in the*    documentation and/or other materials provided with the distribution.** This program is distributed in the hope that it will be useful, but WITHOUT* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for* more details. A copy of the GNU General Public License is available at:* http://www.fsf.org/licensing/licenses*//******************************************************************************                                 vector.h** Class template of vector which is designed for basic linear algebra* operations such as:*              v + k    k + v    v += k    v1 + v2    v1 += v2*              v - k    k - v    v -= k    v1 - v2    v1 -= v2*              v * k    k * v    v *= k    v1 * v2    v1 *= v2*              v / k    k / v    v /= k    v1 / v2    v1 /= v2*              mum,     min,     max       swap       reverse*              norm     dotProd* These operators and functions can be applied to both real vector and* complex vector.** The class also provides the basic math functions such as:*              cos    sin    tan    acos   asin   atan*              abs    exp    log    log10  sqrt   pow* This should include "matrixmath.h" file.** When debugging, use #define BOUNDS_CHECK above your "#include vector.h"* line. When done debugging, comment out #define BOUNDS_CHECK for better* performance.** Zhang Ming, 2010-01 (revised 2010-12), Xi'an Jiaotong University.*****************************************************************************/#ifndef VECTOR_H
#define VECTOR_H#include <iostream>
#include <cassert>
#include <cmath>
#include <complex>
#include <usingdeclare.h>
#include <constants.h>namespace splab
{template <typename Type>class Vector{public:typedef         Type*   iterator;typedef const   Type*   const_iterator;// constructors and destructorVector();Vector( const Vector<Type> &v );Vector( int length, const Type &x = Type(0) );Vector( int length, const Type *array );~Vector();// assignmentsVector<Type>& operator=( const Vector<Type> &v );Vector<Type>& operator=( const Type &x );// accessorsType& operator[]( int i );const Type& operator[]( int i ) const;Type& operator()( int i );const Type& operator()( int i ) const;// iteratorsiterator begin();const_iterator begin() const;iterator end();const_iterator end() const;// type conversionoperator Type*();operator const Type*() const;// othersint size() const;int dim() const;Vector<Type>& resize( int length );// computed assignmentVector<Type>& operator+=( const Type& );Vector<Type>& operator-=( const Type& );Vector<Type>& operator*=( const Type& );Vector<Type>& operator/=( const Type& );Vector<Type>& operator+=( const Vector<Type>& );Vector<Type>& operator-=( const Vector<Type>& );Vector<Type>& operator*=( const Vector<Type>& );Vector<Type>& operator/=( const Vector<Type>& );private:// data pointer for 0-offset indexingType *pv0;// data pointer for 1-offset indexingType *pv1;// the row number of vectorint	 nRow;void init( int length );void copyFromArray( const Type *v );void setByScalar( const Type &x );void destroy();};// class Vector// input and outputtemplate<typename Type>ostream& operator<<( ostream&, const Vector<Type>& );template<typename Type>istream& operator>>( istream&, Vector<Type>& );// arithmetic operatorstemplate<typename Type>Vector<Type> operator-( const Vector<Type>& );template<typename Type>Vector<Type> operator+( const Vector<Type>&, const Type& );template<typename Type>Vector<Type> operator+( const Type&, const Vector<Type>& );template<typename Type>Vector<Type> operator+( const Vector<Type>&, const Vector<Type>& );template<typename Type>Vector<Type> operator-( const Vector<Type>&, const Type& );template<typename Type>Vector<Type> operator-( const Type&, const Vector<Type>& );template<typename Type>Vector<Type> operator-( const Vector<Type>&, const Vector<Type>& );template<typename Type>Vector<Type> operator*( const Vector<Type>&, const Type& );template<typename Type>Vector<Type> operator*( const Type&, const Vector<Type>& );template<typename Type>Vector<Type> operator*( const Vector<Type>&, const Vector<Type>& );template<typename Type>Vector<Type> operator/( const Vector<Type>&, const Type& );template<typename Type>Vector<Type> operator/( const Type&, const Vector<Type>& );template<typename Type>Vector<Type> operator/( const Vector<Type>&, const Vector<Type>& );// dot producttemplate<typename Type>Type dotProd( const Vector<Type>&, const Vector<Type>& );template<typename Type> complex<Type>dotProd( const Vector<complex<Type> >&, const Vector<complex<Type> >& );// utilitiestemplate<typename Type> Type sum( const Vector<Type>& );template<typename Type> Type min( const Vector<Type>& );template<typename Type> Type max( const Vector<Type>& );template<typename Type> Type norm( const Vector<Type>& );template<typename Type> Type norm( const Vector<complex<Type> >& );template<typename Type> void swap( Vector<Type>&, Vector<Type>& );template<typename Type> Vector<Type> linspace( Type, Type, int );template<typename Type> Vector<Type> abs( const Vector<complex<Type> >& );template<typename Type> Vector<Type> arg( const Vector<complex<Type> >& );template<typename Type> Vector<Type> real( const Vector<complex<Type> >& );template<typename Type> Vector<Type> imag( const Vector<complex<Type> >& );template<typename Type>Vector<complex<Type> > complexVector( const Vector<Type>& );template<typename Type>Vector<complex<Type> > complexVector( const Vector<Type>&,const Vector<Type>&  );#include <vector-impl.h>}
// namespace splab#endif
// VECTOR_H

实现文件:

/** Copyright (c) 2008-2011 Zhang Ming (M. Zhang), zmjerry@163.com** This program is free software; you can redistribute it and/or modify it* under the terms of the GNU General Public License as published by the* Free Software Foundation, either version 2 or any later version.** Redistribution and use in source and binary forms, with or without* modification, are permitted provided that the following conditions are met:** 1. Redistributions of source code must retain the above copyright notice,*    this list of conditions and the following disclaimer.** 2. Redistributions in binary form must reproduce the above copyright*    notice, this list of conditions and the following disclaimer in the*    documentation and/or other materials provided with the distribution.** This program is distributed in the hope that it will be useful, but WITHOUT* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for* more details. A copy of the GNU General Public License is available at:* http://www.fsf.org/licensing/licenses*//******************************************************************************                               vector-impl.h** Implementation for Vector class.** Zhang Ming, 2010-01 (revised 2010-12), Xi'an Jiaotong University.*****************************************************************************//*** initialize*/
template <typename Type>
void Vector<Type>::init( int length )
{assert( pv0 == NULL );pv0 = new Type[length];assert( pv0 != NULL );pv1 = pv0 - 1;nRow = length;
}/*** copy vector from normal array*/
template <typename Type>
inline void Vector<Type>::copyFromArray( const Type *v )
{for( int i=0; i<nRow; ++i )pv0[i] = v[i];
}/*** set vector by a scalar*/
template <typename Type>
inline void Vector<Type>::setByScalar( const Type &x )
{for( int i=0; i<nRow; ++i )pv0[i] = x;
}/*** destroy the vector*/
template <typename Type>
void Vector<Type>::destroy()
{if( pv0 == NULL )return;delete []pv0;pv0 = NULL;pv1 = NULL;
}/*** constructors and destructor*/
template <typename Type>
Vector<Type>::Vector()
: pv0(0), pv1(0), nRow(0)
{
}template <typename Type>
Vector<Type>::Vector( const Vector<Type> &v )
: pv0(0), pv1(0), nRow(0)
{init( v.nRow );copyFromArray( v.pv0 );
}template <typename Type>
Vector<Type>::Vector( int length, const Type &x )
:  pv0(0), pv1(0), nRow(0)
{init( length );setByScalar( x );
}template <typename Type>
Vector<Type>::Vector( int length, const Type *array )
:  pv0(0), pv1(0), nRow(0)
{init( length );copyFromArray( array );
}template <typename Type>
Vector<Type>::~Vector()
{destroy();
}/*** overload evaluate operator= from vector to vector*/
template <typename Type>
Vector<Type>& Vector<Type>::operator=( const Vector<Type> &v )
{if( pv0 == v.pv0 )return *this;if( nRow == v.nRow )copyFromArray( v.pv0 );else{destroy();init( v.nRow );copyFromArray( v.pv0 );}return *this;
}/*** overload evaluate operator= from scalar to vector*/
template <typename Type>
inline Vector<Type>& Vector<Type>::operator=( const Type &x )
{setByScalar( x );return *this;
}/*** overload operator [] for 0-offset access*/
template <typename Type>
inline Type& Vector<Type>::operator[]( int i )
{
#ifdef BOUNDS_CHECKassert( 0 <= i );assert( i < nRow );
#endifreturn pv0[i];
}template <typename Type>
inline const Type& Vector<Type>::operator[]( int i ) const
{
#ifdef BOUNDS_CHECKassert( 0 <= i );assert( i < nRow );
#endifreturn pv0[i];
}/*** overload operator () for 1-offset access*/
template <typename Type>
inline Type& Vector<Type>::operator()( int i )
{
#ifdef BOUNDS_CHECKassert( 1 <= i );assert( i <= nRow );
#endifreturn pv1[i];
}template <typename Type>
inline const Type& Vector<Type>::operator()( int i ) const
{
#ifdef BOUNDS_CHECKassert( 1 <= i );assert( i <= nRow );
#endifreturn pv1[i];
}/*** iterators*/
template <typename Type>
inline typename Vector<Type>::iterator Vector<Type>::begin()
{return pv0;
}template <typename Type>
inline typename Vector<Type>::const_iterator Vector<Type>::begin() const
{return pv0;
}template <typename Type>
inline typename Vector<Type>::iterator Vector<Type>::end()
{return pv0 + nRow;
}template <typename Type>
inline typename Vector<Type>::const_iterator Vector<Type>::end() const
{return pv0 + nRow;
}/*** type conversion functions*/
template <typename Type>
inline Vector<Type>::operator Type*()
{return pv0;
}template <typename Type>
inline Vector<Type>::operator const Type*() const
{return pv0;
}/*** get the vector's total size*/
template <typename Type>
inline int Vector<Type>::size() const
{return  nRow;
}/*** get the vector's dimension*/
template <typename Type>
inline int Vector<Type>::dim() const
{return  nRow;
}/*** reallocate vector's size*/
template <typename Type>
Vector<Type>& Vector<Type>::resize( int length )
{if( nRow == length )return *this;destroy();init( length );return *this;
}/*** compound assignment operators +=*/
template <typename Type>
Vector<Type>& Vector<Type>::operator+=( const Type &x )
{iterator itr = (*this).begin();while( itr != (*this).end() )*itr++ += x;return *this;
}template <typename Type>
Vector<Type>& Vector<Type>::operator+=( const Vector<Type> &rhs )
{assert( nRow == rhs.dim() );iterator itrL = (*this).begin();const_iterator itrR = rhs.begin();while( itrL != (*this).end() )*itrL++ += *itrR++;return *this;
}/*** compound assignment operators -=*/
template <typename Type>
Vector<Type>& Vector<Type>::operator-=( const Type &x )
{iterator itr = (*this).begin();while( itr != (*this).end() )*itr++ -= x;return *this;
}template <typename Type>
Vector<Type>& Vector<Type>::operator-=( const Vector<Type> &rhs )
{assert( nRow == rhs.dim() );iterator itrL = (*this).begin();const_iterator itrR = rhs.begin();while( itrL != (*this).end() )*itrL++ -= *itrR++;return *this;
}/*** compound assignment operators *=*/
template <typename Type>
Vector<Type>& Vector<Type>::operator*=( const Type &x )
{iterator itr = (*this).begin();while( itr != (*this).end() )*itr++ *= x;return *this;
}template <typename Type>
Vector<Type>& Vector<Type>::operator*=( const Vector<Type> &rhs )
{assert( nRow == rhs.dim() );iterator itrL = (*this).begin();const_iterator itrR = rhs.begin();while( itrL != (*this).end() )*itrL++ *= *itrR++;return *this;
}/*** compound assignment operators /=*/
template <typename Type>
Vector<Type>& Vector<Type>::operator/=( const Type &x )
{iterator itr = (*this).begin();while( itr != (*this).end() )*itr++ /= x;return *this;
}template <typename Type>
Vector<Type>& Vector<Type>::operator/=( const Vector<Type> &rhs )
{assert( nRow == rhs.dim() );iterator itrL = (*this).begin();const_iterator itrR = rhs.begin();while( itrL != (*this).end() )*itrL++ /= *itrR++;return *this;
}/*** Overload the output stream function.*/
template <typename Type>
ostream& operator<<( ostream &out, const Vector<Type> &v )
{int N = v.dim();out << "size: " << N << " by 1" << "\n";for( int i=0; i<N; ++i )out << v[i] << " " << "\n";return out;
}/*** Overload the input stream function.*/
template <typename Type>
istream& operator>>( istream &in, Vector<Type> &v )
{int N;in >> N;if( !( N == v.dim() ) )v.resize( N );for( int i=0; i<N; ++i )in >> v[i];return in;
}/*** get negative vector*/
template <typename Type>
Vector<Type> operator-( const Vector<Type> &v )
{Vector<Type> tmp( v.dim() );typename Vector<Type>::iterator itrL = tmp.begin();typename Vector<Type>::const_iterator itrR = v.begin();while( itrL != tmp.end() )*itrL++ = -(*itrR++);return tmp;
}/*** vector-scalar addition.*/
template <typename Type>
inline Vector<Type> operator+( const Vector<Type> &v, const Type &x )
{Vector<Type> tmp( v );return tmp += x;
}template <typename Type>
inline Vector<Type> operator+( const Type &x, const Vector<Type> &v )
{return v+x;
}/*** vector-scalar substraction.*/
template <typename Type>
inline Vector<Type> operator-( const Vector<Type> &v, const Type &x )
{Vector<Type> tmp( v );return tmp -= x;
}template <typename Type>
inline Vector<Type> operator-( const Type &x, const Vector<Type> &v )
{Vector<Type> tmp( v );return -tmp += x;
}/*** vector-scalar multiplication.*/
template <typename Type>
inline Vector<Type> operator*( const Vector<Type> &v, const Type &x )
{Vector<Type> tmp( v );return tmp *= x;
}template <typename Type>
inline Vector<Type> operator*( const Type &x, const Vector<Type> &v )
{return v*x;
}/*** vector-scalar division.*/
template <typename Type>
inline Vector<Type> operator/( const Vector<Type> &v, const Type &x )
{Vector<Type> tmp( v );return tmp /= x;
}template <typename Type>
inline Vector<Type> operator/( const Type &x, const Vector<Type> &v )
{int N = v.dim();Vector<Type> tmp( N );for( int i=0; i<N; ++i )tmp[i] = x / v[i];return tmp;
}/*** vector-vector addition.*/
template <typename Type>
inline Vector<Type> operator+( const Vector<Type> &v1, const Vector<Type> &v2 )
{Vector<Type> tmp( v1 );return tmp += v2;
}/*** vector-vector substraction.*/
template <typename Type>
inline Vector<Type> operator-( const Vector<Type> &v1, const Vector<Type> &v2 )
{Vector<Type> tmp( v1 );return tmp -= v2;
}/*** vector-vector multiplication.*/
template <typename Type>
inline Vector<Type> operator*( const Vector<Type> &v1, const Vector<Type> &v2 )
{Vector<Type> tmp( v1 );return tmp *= v2;
}/*** vector-vector division.*/
template <typename Type>
inline Vector<Type> operator/( const Vector<Type> &v1, const Vector<Type> &v2 )
{Vector<Type> tmp( v1 );return tmp /= v2;
}/*** Inner product for vectors.*/
template <typename Type>
Type dotProd( const Vector<Type> &v1, const Vector<Type> &v2 )
{assert( v1.dim() == v2.dim() );Type sum = 0;typename Vector<Type>::const_iterator itr1 = v1.begin();typename Vector<Type>::const_iterator itr2 = v2.begin();while( itr1 != v1.end() )sum += (*itr1++) * (*itr2++);return sum;
}/*** Inner product for vectors.*/
template <typename Type>
complex<Type> dotProd( const Vector<complex<Type> > &v1,const Vector<complex<Type> > &v2 )
{assert( v1.dim() == v2.dim() );complex<Type> sum = 0;typename Vector<complex<Type> >::const_iterator itr1 = v1.begin();typename Vector<complex<Type> >::const_iterator itr2 = v2.begin();while( itr1 != v1.end() )sum += (*itr1++) * conj(*itr2++);return sum;
}/*** Vector's sum.*/
template <typename Type>
Type sum( const Vector<Type> &v )
{Type sum = 0;typename Vector<Type>::const_iterator itr = v.begin();while( itr != v.end() )sum += *itr++;return sum;
}/*** Minimum value of vector.*/
template <typename Type>
Type min( const Vector<Type> &v )
{Type m = v[0];for( int i=1; i<v.size(); ++i )if( m > v[i] )m = v[i];return m;
}/*** Maximum value of vector.*/
template <typename Type>
Type max( const Vector<Type> &v )
{Type M = v[0];for( int i=1; i<v.size(); ++i )if( M < v[i] )M = v[i];return M;
}/*** Vector's norm in Euclidean space.*/
template <typename Type>
Type norm( const Vector<Type> &v )
{Type sum = 0;typename Vector<Type>::const_iterator itr = v.begin();while( itr != v.end() ){sum += (*itr) * (*itr);itr++;}return Type(sqrt(1.0*sum));
}/*** Vector's norm in Euclidean space.*/
template <typename Type>
Type norm( const Vector<complex<Type> > &v )
{Type sum = 0;typename Vector<complex<Type> >::const_iterator itr = v.begin();while( itr != v.end() )sum += norm(*itr++);return Type(sqrt(1.0*sum));
}/*** return vector's reversion*/
template <typename Type>
void swap( Vector<Type> &lhs, Vector<Type> &rhs )
{typename Vector<Type>::iterator itrL = lhs.begin(),itrR = rhs.begin();while( itrL != lhs.end() )std::swap( *itrL++, *itrR++ );
}/*** Generates a vector of n points linearly spaced between and* including a and b.*/
template <typename Type>
Vector<Type> linspace( Type a, Type b, int n )
{if( n < 1 )return Vector<Type>();else if( n == 1 )return Vector<Type>( 1, a );else{Type dx = (b-a) / (n-1);Vector<Type> tmp(n);for( int i=0; i<n; ++i )tmp[i] = a + i*dx;return tmp;}
}/*** Get magnitude of a complex vector.*/
template <typename Type>
Vector<Type> abs( const Vector< complex<Type> > &v )
{Vector<Type> tmp( v.dim() );typename Vector<Type>::iterator itrL = tmp.begin();typename Vector< complex<Type> >::const_iterator itrR = v.begin();while( itrL != tmp.end() )*itrL++ = abs(*itrR++);return tmp;
}/*** Get angle of a complex vector.*/
template <typename Type>
Vector<Type> arg( const Vector< complex<Type> > &v )
{Vector<Type> tmp( v.dim() );typename Vector<Type>::iterator itrL = tmp.begin();typename Vector< complex<Type> >::const_iterator itrR = v.begin();while( itrL != tmp.end() )*itrL++ = arg(*itrR++);return tmp;
}/*** Get real part of a complex vector.*/
template <typename Type>
Vector<Type> real( const Vector< complex<Type> > &v )
{Vector<Type> tmp( v.dim() );typename Vector<Type>::iterator itrL = tmp.begin();typename Vector< complex<Type> >::const_iterator itrR = v.begin();while( itrL != tmp.end() )*itrL++ = (*itrR++).real();return tmp;
}/*** Get imaginary part of a complex vector.*/
template <typename Type>
Vector<Type> imag( const Vector< complex<Type> > &v )
{Vector<Type> tmp( v.dim() );typename Vector<Type>::iterator itrL = tmp.begin();typename Vector< complex<Type> >::const_iterator itrR = v.begin();while( itrL != tmp.end() )*itrL++ = (*itrR++).imag();return tmp;
}/*** Convert real vector to complex vector.*/
template <typename Type>
Vector<complex<Type> > complexVector( const Vector<Type> &rv )
{int N = rv.dim();Vector<complex<Type> > cv( N );typename Vector<complex<Type> >::iterator itrL = cv.begin();typename Vector<Type>::const_iterator itrR = rv.begin();while( itrR != rv.end() )*itrL++ = *itrR++;return cv;
}template <typename Type>
Vector<complex<Type> > complexVector( const Vector<Type> &vR,const Vector<Type> &vI )
{int N = vR.dim();assert( N == vI.dim() );Vector<complex<Type> > cv( N );typename Vector<complex<Type> >::iterator itrC = cv.begin();typename Vector<Type>::const_iterator itrR = vR.begin(),itrI = vI.begin();while( itrC != cv.end() )*itrC++ = complex<Type>( *itrR++, *itrI++ );return cv;
}

测试代码:

/******************************************************************************                               vector_test.cpp** Vector class testing.** Zhang Ming, 2010-01 (revised 2010-12), Xi'an Jiaotong University.*****************************************************************************/#define BOUNDS_CHECK#include <iostream>
#include <iomanip>
#include <complex>
#include <vector.h>using namespace std;
using namespace splab;const int M = 3;void display( const int *p, int length )
{for( int i=0; i<length; ++i )cout << p[i] << "\t" ;cout << endl;
}int main()
{int k;int arrays[3] = {1,2,3};Vector<int> v1( M,arrays );k = 1;Vector<int> v2( M,k );Vector<int> v3( M );k = 0;v3 = k;Vector<int> v4( v1 );cout << "vector v1 : " << v1 << endl;cout << "vector v2 : " << v2 << endl;cout << "vector v3 : " << v3 << endl;cout << "vector v4 : " << v4 << endl;display( v4, M );cout << endl;v4.resize( 5 );Vector<int>::iterator itr = v4.begin();while( itr != v4.end() )*itr++ = 1;cout << "new vector v4 : " << v4 << endl;v4 = v1;cout << "new vector v4 : " << v4 << endl;k = 2;v3 = k+v1;cout << "v3 = k + v1 : " << v3 << endl;v3 += k;cout << "v3 += k : " << v3 << endl;v3 = v1-k;cout << "v3 = v1 - k : " << v3 << endl;v3 = k-v1;cout << "v3 = k - v1 : " << v3 << endl;v3 -= k;cout << "v3 -= k : " << v3 << endl;v3 = k*v1;cout << "v3 = k * v1 : " << v3 << endl;v3 *= k;cout << "v3 *= k : " << v3 << endl;v3 = v1/k;cout << "v3 = v1 / k : " << v3 << endl;v3 = k/v1;cout << "v3 = k / v1 : " << v3 << endl;v3 /= k;cout << "v3 /= k : " << v3 << endl;v3 = v1+v2;cout << "v3 = v1 + v2 : " << v3 << endl;v3 += v1;cout << "v3 += v1 : " << v3 << endl;v3 = v1-v2;cout << "v3 = v1 - v2 : " << v3 << endl;v3 -= v1;cout << "v3 -= v1 : " << v3 << endl;v3 = v1*v2;cout << "v3 = v1 * v2 : " << v3 << endl;v3 *= v1;cout << "v3 *= v1 : " << v3 << endl;v3 = v1/v2;cout << "v3 = v1 / v2 : " << v3 << endl;v3 /= v1;cout << "v3 /= v1 : " << v3 << endl;cout << "minimum element of v1 :   " << min(v1) << endl << endl;cout << "maximum element of v1 :   " << max(v1) << endl << endl;cout << "L2 norm of v3 :   " << norm( v3 ) << endl << endl;cout << "inner product of v1 and v2 :   " << dotProd( v1, v2 ) << endl << endl;complex<double> z = -1.0;Vector< complex<double> > v( M );v[0] = polar( 1.0,PI/4 );v[1] = polar( 1.0,PI );v[2] = complex<double>( 1.0,-1.0 );Vector< complex<double> > u = v*z;cout << setiosflags(ios::fixed) << setprecision(4);cout << "convert from real to complex vector: " << complexVector(v3) << endl;cout << "convert from real to complex vector: " << complexVector(v3,-v1) << endl;cout << "complex vector v : " << v << endl;cout << "complex vector u = -v : " << u << endl;cout << "norm of coplex vector v : " << norm(v) << endl << endl;cout << "dot product of complex vector v and 1+u: " << dotProd(v,u-z) << endl << endl;int N = 5;Vector<double> x = linspace( 0.0, TWOPI, N );Vector< complex<float> > cv(N);for( int i=0; i<N; ++i )cv[i] = complex<float>( float(sin(x[i])), float(cos(x[i])) );cout << "Complex vector vc : " << cv << endl;cout << "Absolute of vc : " << abs(cv) << endl;cout << "Angle of vc : " << arg(cv) << endl;cout << "Real part of vc : " << real(cv) << endl;cout << "Imaginary part of vc : " << imag(cv) << endl;cout << resetiosflags(ios::fixed);Vector< Vector<double> > v2d1( M );for( int i=0; i<M; ++i ){v2d1[i].resize( M );for( int j=0; j<M; ++j )v2d1[i][j] = double( i+j );}cout << "two dimension vector v2d1 : " << endl;Vector< Vector<double> >::const_iterator itrD2 = v2d1.begin();int rowNum = 0;while( itrD2 != v2d1.end() )cout << "the " << rowNum++ << "th row : " << *itrD2++ << endl;Vector< Vector<double> > v2d2 = v2d1+v2d1;cout << "two dimension vector v2d2 = v2d1 + v2d1 : " << v2d2;return 0;
}

运行结果:

size: 5 by 1
0.0000
1.5708
3.1416
4.7124
6.2832sin of x : size: 5 by 1
0.0000
1.0000
0.0000
-1.0000
-0.0000cos of x : size: 5 by 1
1.0000
0.0000
-1.0000
-0.0000
1.0000tan of x : size: 5 by 1
0.0000
16331778728383844.0000
-0.0000
5443926242794615.0000
-0.0000asin of x : size: 5 by 1
0.0000
nan
nan
nan
nanacos of x : size: 5 by 1
1.5708
nan
nan
nan
nanatan of x : size: 5 by 1
0.0000
1.0039
1.2626
1.3617
1.4130exp of x : size: 5 by 1
1.0000
4.8105
23.1407
111.3178
535.4917log of x : size: 5 by 1
-inf
0.4516
1.1447
1.5502
1.8379log10 of x : size: 5 by 1
-inf
0.1961
0.4971
0.6732
0.7982sqrt of x : size: 5 by 1
0.0000
1.2533
1.7725
2.1708
2.5066pow of x : size: 5 by 1
1.0000
2.0327
36.4622
1487.9012
103540.9204pow of x : size: 5 by 1
0.0000
2.4674
9.8696
22.2066
39.4784pow of x : size: 5 by 1
1.0000
2.9707
8.8250
26.2162
77.8802The standard normal distribution : size: 5 by 1
0.0604
0.0633
0.0625
0.0578
0.0503Process returned 0 (0x0)   execution time : 0.078 s
Press any key to continue.

转载于:https://my.oschina.net/zmjerry/blog/3006

相关文章:

C# 篇基础知识11——泛型和集合

.NET提供了一级功能强大的集合类&#xff0c;实现了多种不同类型的集合&#xff0c;可以根据实际用途选择恰当的集合类型。 除了数组 Array 类定义在System 命名空间中外&#xff0c;其他的集合类都定义在System.Collections 命名空间中。为了方便、快捷地操纵集合元素&#xf…

React和vue的差异和相似地方

React 单向绑定&#xff08;加插件后&#xff0c;还是可以双向绑定&#xff09; Vue 双向绑定 组件化 1、 React&#xff0c;需要编写render函数&#xff0c; 2、 当React状态的状态state改变是render就会重新被调用&#xff0c; 重新计算全dom&#xff0c;然后对旧的dom就行对…

正则表达式相关方法

1 判断字符串中是否包含字母 /** * 使用正则表达式来判断字符串中是否包含字母 * param str 待检验的字符串 * return 返回是否包含 * true: 包含字母 ;false 不包含字母*/ public boolean judgeContainsStr(String str) { String regex".*[a-zA-Z].*"; Match…

Ajax Upload多文件上传插件翻译及中文演示

http://www.zhangxinxu.com/wordpress/?p342转载于:https://www.cnblogs.com/qiantuwuliang/archive/2010/03/19/1689800.html

[每日一讲] Python系列:Python概述

Python 序章 概述 Python 是弱类型动态解释型的面向对象高级语言&#xff0c;其具备面向对象的三大特点&#xff1a;封装、继承、多态。Python 代码运行时&#xff0c;其有一个编译过程&#xff0c;通过编译器生成 .pyc 字节码 文件&#xff08;为二进制文件&#xff09;&#…

微信公众号开发 微信消息回复开发 文本消息 图片消息开发

开发语言&#xff1a;java 实现功能&#xff1a;发送文字回复文字&#xff0c;发送图片回复图片、token验证、获取access_token等相关功能。 如图&#xff1a; 微信后台接口配置 &#xff0c;此为测试账号&#xff0c;正式设置也是一样的 项目地址&#xff1a;https://github…

[置顶]2010年东北大学ACM程序设计竞赛冬季校赛题解

8题只做出4题比较easy的题&#xff0c;而且做得挺麻烦&#xff0c;看来还要多练练。 AC的题如下 NEUOJ 1112 I Love Apple DescriptionSo many people love apple and there is a problem about apple.An Apple Word is a word that consists of only the letters A, P, L, an…

生成唯一序列号

写一个存储过程来实现&#xff1a; 转载于:https://www.cnblogs.com/hwgok/p/8136750.html

如何改变一个地图的Zoom单位

mapControl1.Map.Zoom new MapInfo.Geometry.Distance(mapControl1.Map.Zoom.value,MapInfo.Geometry.DistanceUnit.Kilometer);也可以分开写成如下格式&#xff1a;MapInfo.Geometry.Distance d new MapInfo.Geometry.Distance(1000, DistanceUnit.Kilometer);mapControl1.M…

canvas上的像素操作(图像复制,细调)

canvas上的像素操作(图像复制&#xff0c;细调) 总结 1、操作对象&#xff1a;ImageData 对象&#xff0c;其实是canvas的像素点集合 2、主要操作&#xff1a; var objctx.getImageData(0,0,100,100); ctx.putImageData(obj,110,0) 3、操作图片要放在站点才能正常操作&#xf…

sql查询返回xml数据之应用【转载】

sql查询返回xml数据之应用【转载】 今天查看邮件&#xff0c;看到一标题Using the FOR XML Clause to Return Query Results as XML&#xff0c;点进去看了看&#xff0c;以前也是知道sql server 查询可以返回xml格式&#xff0c;但具体一到应用中比较少&#xff0c;读过文章后…

solr 实现对经纬度的查询

1、solr版本 solr7 2、solr 经纬度查询的方式 使用LatLonType(用于平面坐标&#xff0c;而不是大地坐标&#xff09;SpatialRecursivePrefixTreeFieldType&#xff08;缩写为RPT&#xff09;BBoxField&#xff08;用于边界索引查询&#xff09;2.1 使用 LatLonPointSpatialF…

win7关于IIS发布网站时候数据库的问题,xp也一样

Win7装iis极其简单. 添加ASP.NET网站时应该选择添加"添加应用程序" 如果要连接sql server会报错,说是 "无法打开登录所请求的数据库 "MarketDept"。登录失败。用户 IIS APPPOOL\DefaultAppPool 登录失败。" 而系统中根本不会存在这个用户的. 解决…

Linq 等式运算符:SequenceEqual

检查元素的数量&#xff0c;每个元素的值及两个集合中元素的顺序是否相等,3个方面都相等则为true,否则为false IList<string> strList1 new List<string>(){"One", "Two", "Three", "Four", "Three"};IList<…

Swing 实现聊天系统 私发与群发

该系统使用的了socket、swing相关知识&#xff0c;实现了一个简单的群聊和私聊的系统。 1、程序界面功能展示 服务端swing界面展示 客户端服务展示 用户上线与发送消息客户端与服务端 私发消息 相关代码&#xff1a; package frame;import java.awt.BorderLayout; import ja…

Http和Socket连接区别(ZT)

1、TCP连接 要想明白Socket连接&#xff0c;先要明白TCP连接。手机能够使用联网功能是因为手机底层实现了TCP/IP协议&#xff0c;可以使手机终端通过无线网络建立TCP连接。TCP协议可以对上层网络提供接口&#xff0c;使上层网络数据的传输建立在“无差别”的网络之上。 建立起一…

函数传参涉及到副本的创建与拷贝问题分析

遇到一个问题,是这样的: b [1, 2, 3]def aaa(b):b.append(4)def bbb(b):b 5aaa(b) print(b) # [1, 2, 3, 4]bbb(b) print(b) # [1, 2, 3, 4] 为什么呢,为什么通过函数传参,去修改参数,结果不一致呢? 原因是因为函数传参涉及到了参数副本的创建与拷贝,具体详解: 圆圈2为传参…

网页鼠标滚动实现图片缩放

<SCRIPT LANGUAGE"JavaScript"><!--//图片按比例缩放,可输入参数设定初始大小function resizeimg(ImgD,iwidth,iheight) {var p_w_picpathnew Image();p_w_picpath.srcImgD.src;if(p_w_picpath.width>0 && p_w_picpath.height>0){if(p_w_picp…

Dubbo 2.7.1 踩坑记

Dubbo 2.7 版本增加新特性&#xff0c;新系统开始使用 Dubbo 2.7.1 尝鲜新功能。使用过程中不慎踩到这个版本的 Bug。 系统架构 Spring Boot 2.14-Release Dubbo 2.7.1 现象 Dubbo 服务者启动成功&#xff0c;正常提供服务&#xff0c;消费者调用偶现失败的情况。错误如下图: …

经典算法研究系列:二、Dijkstra 算法初探

经典算法研究系列&#xff1a;二、Dijkstra 算法初探 July 二零一一年一月 本文主要参考&#xff1a;算法导论 第二版、维基百科。 写的不好之处&#xff0c;还望见谅。本经典算法研究系列文章&#xff0c;永久勘误&#xff0c;永久更新、永久维护。 July、二零一一年二月…

[Python Study Notes] Python的安装

Windows&#xff1a; 1.下载安装包&#xff1a; 转到Python官网https://www.python.org/downloads/ &#xff0c;下载最新版本的Python。 2.安装 安装到自定义的安装路径下。 3.配置环境变量 安装完成后--》【右键快捷方式】--》【复制python路径】&#xff0c;例如&#xff1…

swing 实现电影选座系统

该系统使用swing数据库 实现一个电影选座系统&#xff0c;相关系统的截图如下 使用三层架构实现电影购票系统&#xff0c;分用户和管理员&#xff0c;用户功能:展示电影&#xff0c;查找电影(模糊查询)&#xff0c;查看电影详情&#xff0c;查找场次&#xff0c;购买影票&…

JS动态加载JS

1、直接document.write <script language"javascript"> document.write("<script srctest.js><\/script>"); </script> 2、动态改变已有script的src属性 <script src id"s1"></script> <script lang…

PAT乙级1037

1037 在霍格沃茨找零钱 (20 分)如果你是哈利波特迷&#xff0c;你会知道魔法世界有它自己的货币系统 —— 就如海格告诉哈利的&#xff1a;“十七个银西可(Sickle)兑一个加隆(Galleon)&#xff0c;二十九个纳特(Knut)兑一个西可&#xff0c;很容易。”现在&#xff0c;给定哈利…

SAD和SATD的区别[摘]

Q:如果不用率失真最优化&#xff0c;为什么选择SATD&#xff0b;deltar&#xff08;mv&#xff0c;mode&#xff09;作为模式选择的依据&#xff1f;为什么运动估计中&#xff0c;整象素搜索用SAD&#xff0c;而亚象素用SATD&#xff1f;为什么帧内模式选择要用SATD&#xff1f…

照片换色 使用Python 或者 java

记录使用第三方api 给照片换底色&#xff0c;智能抠图。 1、第三方接口地址 https://www.remove.bg/api 2、抠图效果 3、使用python 实现的代码 在网页换色是不需要进行注册的&#xff0c;如果自己开发 需要注册账号 &#xff0c;得到调取api的口令 import requests impor…

WEB安全,SQL注入漏洞的加固代码汇总

该修复任务专用于处理以下安全性问题&#xff1a;[1] SQL 盲注[2] SQL 注入[3] XPath 注入[4] 发现数据库错误模式[5] 跨站点脚本编制[6] 使用 SQL 注入的认证旁路[7] HTTP 响应分割[8] 链接注入&#xff08;便于跨站请求伪造&#xff09;详细信息若干问题的补救方法在于对用户…

mui ios中form表单中点击输入框头部导航栏被推起及ios中form表单中同时存在日期选择及输入框时,日历选择页面错乱bug...

一、ios header导航栏被推起解决方法 1 设置弹出软键盘时自动改变webview的高度 plus.webview.currentWebview().setStyle({ softinputMode: "adjustResize" // 弹出软键盘时自动改变webview的高度 }); 2 增加样式 html, body { height: 100%; margin: 0px; …

qt试用1(Eclipse+cdt+Qt)

下载eclipse-cpp-helios-SR1-win32.zip下载Qt下载qt-eclipse-integration-win32-1.6.1.exe写一个启动eclipse的batch文件C:\program\eclipse-cpp-helios-SR1-win32\eclipse\cdt.batset path%path%;C:\Qt\2010.05\mingw\binset LIBRARY_PATHC:\Qt\2010.05\mingw\libset C_INCLUD…

Solr 中遇到的问题

1、问题1 &#xff1a;whose UTF8 encoding is longer than the max length 32766 Error from server at http://localhost:8983/solr/newcore: Exception writing document id 995 to the index; possible analysis error: Document contains at least one immense term in f…