I am trying to implement a simple matlab-like array (now only one dimension actually), what I tried to do is to implement the following matlab codes:
a=1:10;
ind=find(a>5);
a[ind]=5;
I know that the std has valarray to do this through a slice array. I do not know much details on it. The code is:
#include <iostream>
using namespace std;
template <typename T> class array
{
public:
int m,n; //two dimensional at most
T *pdata;
//construct the array
array(){m=n=0;pdata=NULL;} //default is empty matrix
array(T a){m=n=1;pdata=new T[1];*pdata=a;} //array for scalar: array a=10;
array(int m0,int n0=1) {m=m0;n=1;pdata=new T[m];}
array(const array& a,int len=-1);
//destructor
~array() {delete []pdata;}
//operator overloading
array<T>& operator+=(T s);
T& operator[](int i) {return pdata[i];}
array<T>& operator[](array<int> ind);
array<T>& operator=(const array<T>& a);
array<T>& operator=(T a) {for(int i=0;i<m;i++) pdata[i]=a;return *this;}
array<bool> operator>(T a);
array<bool> operator<(T a);
array<bool> operator==(T a);
};
//copy a part of the other array
template <typename T> array<T>::array<T>(const array<T>& a,int len)
{
if(len==-1) len=a.m*a.n;
if(len==0) {m=0;n=0;pdata=NULL;}
if(len>0)
{
m=len;n=1;
pdata=new T[len];
for(int i=0;i<len;i++) pdata[i]=a.pdata[i];
}
}
template <typename T> array<T>& array<T>::operator +=(T s)
{
for(int i=0;i<m*n;i++) pdata[i]+=s;
return *this;
}
//this function does not meet the purpose, it returns a reference to a temp obj
template <typename T> array<T>& array<T>::operator[](array<int> ind)
{
array<T> ret(ind.m,ind.n);
for(int i=0;i<ind.m*ind.n;i++)
{
ret.pdata[i] = pdata[ind.pdata[i]];
}
return ret;
}
template <typename T> array<bool> array<T>::operator>(T a)
{
array<bool> res(m*n);
for(int i=0;i<m*n;i++) res.pdata[i]=pdata[i]>a;
return res;
}
//helper function
array<int> find(array<bool> a)
{
array<int> ret(a.m,a.n); //first use the same size space
int len=0;
for(int i=0;i<a.m*a.n;i++)
{
if(a.pdata[i]) {ret.pdata[len]=i;len++;}
}
return array<int>(ret,len);
}
/*ostream& operator<<(array<T>& a)
{
ostream os;
for(int i=0;i<a.m*a.n;i++) os>>a[i]>>'\t';
return os;
}*/
int main()
{
array<float> a(10);
for(int i=0;i<10;i++) a[i]=i;
for(i=0;i<10;i++) cout<<a[i]<<'\t';
cout<<endl;
array<int> ind=find(a>5);
for(i=0;i<ind.m;i++) cout<<ind[i]<<'\t';
cout<<endl;
a[ind]=5;//this will not work on the original array
//how do we support this????undefined
for(i=0;i<10;i++) cout<<a[i]<<'\t';
cout<<endl;
return 0;
}
The final a is not changed at all since we are working on a temp array.
I know the function operator"> is not properly implemented, but I do not know how to do this. Anyone can give me a hint? Thanks
I would create an ArraySlice class, and return an instance of that from operator []. This class would have a reference to the original Array, and would need to re-implement most members as forward calls to the Array. For instance, ArraySlice::operator[] would call Array::operator[] with the appropriate index.
I think that for shared arrays the best solution is to have a single type for both the original (full) matrix and the "views".
By parametrizing the element access you can have the same generic code work for both, also if you add an optional std::vector element inside the class that will contain the actual data for the original full matrix then memory handling becomes automatic.
This is a small implementation of this idea... for the selection I've used an std::vector of pairs of integers; assigning to ArraySelection will use the element access operator so it will work both for the original matrix or for views.
The main program allocates a 10x10 matrix, and then creates four different 5x5 views with elements with coordinates that are even/even, even/odd, odd/even and odd/odd.
Those views are set to 4 different constant values.
Then a selection is done on the full matrix and an assignment is done on the selected elements. Finally the original full matrix is printed.
#include <stdexcept>
#include <vector>
#include <functional>
#include <algorithm>
#include <stdio.h>
typedef std::vector< std::pair<int, int> > Index;
template<typename T>
struct Array;
template<typename T>
struct ArraySelection
{
Array<T>& a;
Index i;
ArraySelection(Array<T>& a)
: a(a)
{
}
ArraySelection& operator=(const T& t)
{
for (int j=0,n=i.size(); j<n; j++)
a(i[j].first, i[j].second) = t;
return *this;
}
};
template<typename T>
struct Array
{
int rows, cols;
std::vector<T*> rptr;
int step;
std::vector<T> data; // non-empty if data is owned
T& operator()(int r, int c)
{
return rptr[r][c * step];
}
Array(int rows, int cols,
Array *parent = NULL,
int row0=0, int rowstep=1,
int col0=0, int colstep=1)
: rows(rows), cols(cols), rptr(rows)
{
if (parent == NULL)
{
// Owning matrix
data.resize(rows*cols);
for (int i=0; i<rows; i++)
rptr[i] = &data[i*cols];
step = 1;
}
else
{
// View of another matrix
for (int i=0; i<rows; i++)
rptr[i] = &((*parent)(row0 + i*rowstep, col0));
step = colstep;
}
}
template<typename F>
ArraySelection<T> select(const F& f)
{
Index res;
for (int i=0; i<rows; i++)
for (int j=0; j<cols; j++)
if (f((*this)(i, j)))
res.push_back(std::make_pair(i, j));
ArraySelection<T> ar(*this);
ar.i.swap(res);
return ar;
}
// Copy construction of a full matrix makes a full matrix,
// Copy construction of a view creates a view
Array(const Array& other)
: rows(other.rows), cols(other.cols), rptr(other.rptr), step(other.step)
{
if (other.data)
{
data = other.data;
for (int i=0; i<rows; i++)
rptr[i] = &data[i*cols];
}
}
// Assignment is element-by-element optionally with conversion
template<typename U>
Array& operator=(const Array<U>& other)
{
if (other.rows != rows || other.cols != cols)
throw std::runtime_error("Matrix size mismatch");
for(int i=0; i<rows; i++)
for (int j=0; j<cols; j++)
(*this)(i, j) = other(i, j);
return *this;
}
};
int main()
{
Array<double> a(10, 10);
Array<double> a00(5, 5, &a, 0, 2, 0, 2);
Array<double> a01(5, 5, &a, 0, 2, 1, 2);
Array<double> a10(5, 5, &a, 1, 2, 0, 2);
Array<double> a11(5, 5, &a, 1, 2, 1, 2);
for (int i=0; i<5; i++)
for (int j=0; j<5; j++)
{
a00(i, j) = 1.1;
a01(i, j) = 2.2;
a10(i, j) = 3.3;
a11(i, j) = 4.4;
}
a.select(std::binder2nd< std::greater<double> >(std::greater<double>(), 3.5)) = 0;
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
printf(" %0.3f", a(i, j));
}
printf("\n");
}
return 0;
}
Andrea, Thank you for the hint. Mostly what you said makes sense and really helps. I create another ind_array and keep the original array's address and now it works!
The only change is the operator[] now returns the ind_array. and the operator= for ind_array is defined to do the real assignment. (to make it simple, I now removed the second dimension)
Here is the modified code:
#include <iostream>
using namespace std;
template <typename T> class ind_array;
template <typename T> class array
{
public:
int len; //two dimensional at most
T *pdata;
//construct the array
array(){len=0;pdata=NULL;} //default is empty matrix
//array(T a){len=1;pdata=new T[1];*pdata=a;} //array for scalar: array a=10;
array(int m0) {len=m0;pdata=new T[len];}
array(const array& a,int len0=-1);
//destructor
~array() {delete []pdata;}
int size() const {return len;}
//operator overloading
array<T>& operator+=(T s);
T& operator[](int i) {return pdata[i];}
ind_array<T> operator[](const array<int>& ind);//{return (ind_array(ind,pdata));}
array<T>& operator=(const array<T>& a);
array<T>& operator=(T a) {for(int i=0;i<len;i++) pdata[i]=a;return *this;}
array<bool> operator>(T a);
array<bool> operator<(T a);
array<bool> operator==(T a);
};
//Index array or similar indirect-array as in valarray
//this class shall keeps the array's address and the index
template <typename T> class ind_array
{
array<int> ind; //an index array
T* ptr; //a pointer to the original data
public:
int size() const {return ind.size();}
void operator=(T a){for(int i=0;i<size();i++) ptr[ind[i]]=a;} //assignment a value to a subarray
//how to construct the indx array then?
//according to valarry, the default constructor shall be prohibited
ind_array(const array<int>& indx,T* pt):ind(indx),ptr(pt){} //default constructor
};
//copy a part of the other array
template <typename T> array<T>::array<T>(const array<T>& a,int len0)
{
if(len0==-1) len0=a.len;
if(len0==0) {len=0;pdata=NULL;}
if(len0>0)
{
len=len0;
pdata=new T[len];
for(int i=0;i<len;i++) pdata[i]=a.pdata[i];
}
}
template <typename T> array<T>& array<T>::operator +=(T s)
{
for(int i=0;i<len;i++) pdata[i]+=s;
return *this;
}
//this function does not meet the purpose, it returns a reference to a temp obj
//now we change it to return a indx_array which stores the original array's address
template <typename T> ind_array<T> array<T>::operator[](const array<int>& ind)
{
/*array<T> ret(ind.len);
for(int i=0;i<ind.len;i++)
{
ret.pdata[i] = pdata[ind.pdata[i]];
}
return ret;*/
return (ind_array<T>(ind,pdata)); //call the constructor
}
template <typename T> array<bool> array<T>::operator>(T a)
{
array<bool> res(len);
for(int i=0;i<len;i++) res.pdata[i]=pdata[i]>a;
return res;
}
//helper function
array<int> find(array<bool> a)
{
array<int> ret(a.len); //first use the same size space
int len=0;
for(int i=0;i<a.len;i++)
{
if(a.pdata[i]) {ret.pdata[len]=i;len++;}
}
return array<int>(ret,len);
}
/*ostream& operator<<(array<T>& a)
{
ostream os;
for(int i=0;i<a.m*a.n;i++) os>>a[i]>>'\t';
return os;
}*/
int main()
{
array<float> a(10);
for(int i=0;i<10;i++) a[i]=i;
for(i=0;i<10;i++) cout<<a[i]<<'\t';
cout<<endl;
array<int> ind=find(a>5);
for(i=0;i<ind.len;i++) cout<<ind[i]<<'\t';
cout<<endl;
a[ind]=5;//this will not work on the original array
//how do we support this????undefined
for(i=0;i<10;i++) cout<<a[i]<<'\t';
cout<<endl;
return 0;
}
Related
I want to clear a priority vector class, which works like priority_queue but is vector based. I want to use [] operator for accessing an element of the vector, I did something but the program just keep crashing. Any suggestions?
#include<iostream>
#include<vector>
#include<typeinfo>
using namespace std;
string first (string a, string b){
int siz = min(a.size(), b.size());
int place = 0;
while (a[place]==b[place] && place<siz){
place++;
}
if (a[place]>b[place]){
return b;
}
else if (a[place]<b[place]){
return a;
}
}
template <class type>
class priority_vector{
public:
type check;
string check2;
vector <type> pv;
bool isString(){
if (typeid(type).name()==typeid(check2).name()){return true;}
else {return false;}
}
void push_in(type input){
if (isString()){
if (pv.size()==0){
pv.push_back(input);
}
else{
vector <type> :: iterator vit;
vit = pv.begin();
while (first(*pv, input)==*pv){
pv ++;
}
vit.insert(vit, input);
}
}
else{
if(pv.size()==0){
pv.push_back(input);
}
else{
vector <type> :: iterator vit;
vit = pv.begin();
while (*pv<input){
pv++;
}
vit.insert(vit, input);
}
}
}
type operator[](int a){
return pv[a];
}
};
int main(){
priority_vector <string> v_s;
int n;
cin>>n;
int in;
for (int i=0; i<n; i++){
cin>>n;
v_s.push_in(n);
}
for (int i=0; i<n; i++){
cout<<v_s[i];
}
return 0;
}
The std::priority_queue container adaptor by default uses std::vector. What's more interesting is that std::priority_queue is actually one of the few standard classes designed to be inherited.
That means you can easily do something like
template<typename T>
class priority_vector : public std::priority_queue<T>
{
public:
// Constructors...
T const& operator[](size_t idx) const
{
return c[idx];
}
T& operator[](size_t idx)
{
return c[idx];
}
};
// stdafx.h
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
using namespace std;
#include "Animal.h"
// TODO: reference additional headers your program requires here
class Animal
{
private:
int itsWeight;
public:
Animal(int);
Animal();
~Animal() {}
int getWeight() const { return itsWeight; }
void Display() const;
};
template <class T>
class Array
{
private:
T *pType;
int itsSize;
const int defaultSize = 10;
public:
//constructors
Array(int itsSize = defaultSize);
Array(const Array &rhs);
~Array() { delete[] pType; }
//operators
Array& operator=(const Array&);
T& operator[](int offSet){ return pType[offSet]; }
const T& operator[](int offSet) const { return pType[offSet]; }
//methods of Access
int getSize() const { return itsSize; }
};
//constructor
template <class T>
Array<T>::Array(int size) :
itsSize(size)
{
pType = new T[size];
for (int i = 0; i < size; i++)
{
pType[i] = 0;
}
}
//copy-constructor
template <class T>
Array<T>::Array(const Array &rhs)
{
itsSize = rhs.getSize();
pType = new T[itsSize];
for (int i = 0; i < itsSize; i++)
{
pType[i] = rhs[i];
}
}
//operator prisvoeniya
template <class T>
Array<T>& Array<T>::operator=(const Array &rhs)
{
if (this == &rhs)
return *this;
delete[] pType;
itsSize = rhs.getSize();
pType = new T[itsSize];
for (int i = 0; i < itsSize; i++)
{
pType[i] = rhs[i];
}
return *this;
}
//this is the file "Animal.cpp"
#include "stdafx.h"
#include "Animal.h"
Animal::Animal()
{
itsWeight = 0;
}
Animal::Animal(int weight)
{
itsWeight = weight;
}
void Animal::Display() const
{
cout << itsWeight;
}
// the main function
#include "stdafx.h"
int_tmain(int argc, _TCHAR* argv[])
{
Array<int> theArray; //Integer array
Array<Animal> theZoo; //Animal array
Animal *pAnimal;
//filling the array
for (int i = 0; i < theArray.getSize(); i++)
{
theArray[i] = i * 2;
pAnimal = new Animal[i * 3];
theZoo[i] = *pAnimal;
delete pAnimal;
}
for (int j = 0; j < theArray.getSize(); j++)
{
cout << "theArray[" << j << "]:\t";
cout << theArray[j]<<"\t\t";
cout << "theZoo[" << j << "]:\t";
theZoo[j].Display();
cout << endl;
}
return 0;
}
The problem is that: The compiler gives me the errors
Error 1 error C2648: 'Array<int>::defaultSize' : use of member as default parameter requires static member
d:\documents\work\c++ files\tigrans\homework10\templates\templates\templates\animal.h 28 1 Templates
Error 2 error C2648: 'Array<Animal>::defaultSize' : use of member as default parameter requires static member
d:\documents\work\c++ files\tigrans\homework10\templates\templates\templates\animal.h 28 1 Templates
Anybody can help me to understand that. I change the
const int defaultSize=10;
to
static const int defaultSize=10
then there is not errors but in that time show Debug Assertion Failed!
This part of your code is dodgy
{
pAnimal = new Animal[i * 3];
theZoo[i] = *pAnimal;
delete pAnimal;
}
The first line allocates an array of i*3 Animals, using their default constructor (which makes an Animal with itsWeight=0). In the second line you assign the first these newly allocated Animals to theZoo[i]. Finally, the third line tries to de-allocate the Animals.
The last line contains an error, since you call delete on a pointer obtained with new [].
The whole concept of creating objects on the heap only to immediately destroy them is quite dubious -- perhaps you come from another programming language, where this is the only way to create things? First, you could simply use an automatic variable
{
Animal a; // or a(i*3);
theZoo[i] = a;
}
or yet briefer
{
theZoo[i] = Animal(i*3);
}
(Note the if you would use a std container, you could say theZoo.emplace_back(i*3);, avoiding the copy of Animal.)
Hi I'm implementing a matrix class in c++
I know that there are great libraries that do that like opencv but I need to do that myself.
For example if I implement the sum I can do like this
class Mat{
public:
double* data;
int rows,cols;
Mat(int r,int c):rows(r),cols(c){
data = new double[r*c];
}
};
void Sum(Mat& A,Mat& B,Mat& C){
for (int i = 0; i < A.rows*A.cols; ++i){
C.data[i] = A.data[i]+B.data[i];
}
}
int main(){
//Allocate Matrices
Mat A(300,300);
Mat B(300,300);
Mat C(300,300);
//do the sum
sum(A,B,C);
}
I would like to get something more readable like this but without losing efficiency
C = A + B
This way C is reallocated every time and I don't want that
Thank you for your time
Delay the calculation.
class MatAccess {
friend class Mat;
friend class MatOpAdd;
virtual double operator[](int index) const = 0;
};
class MatOpAdd: public MatAccess {
friend class Mat;
private:
const MatAccess& left;
const MatAccess& right;
MatOpAdd(const MatAccess& left, const MatAccess& right):
left(left), right(right) {}
double operator[](int index) const {
return left[index] + right[index];
}
};
class Mat: public MatAccess{
public:
double* data;
int rows,cols;
Mat(int r,int c):rows(r),cols(c){
data = new double[r*c];
}
MatOpAdd operator +(const MatAccess& other) {
return MatOpAdd(*this, other);
}
const Mat& operator = (const MatAccess& other) {
for(int i = 0; i < rows*cols; ++i) {
data[i] = other[i];
}
return *this;
}
private:
double operator[](int index) const {
return data[index];
}
double& operator[](int index) {
return data[index];
}
};
int main(){
//Allocate Matrices
Mat A(300,300);
Mat B(300,300);
Mat C(300,300);
//do the sum
C = A + B;
}
Now the '+' calculation will be done in the "operator="
Things I would change:
MatAccess should include the dimensions (rows,cols).
Mat adding constructors and operator= or make it not copyable
Mat::operator+ and Mat::operator= check for equal rows,col
delete memory when not used anymore or
use std::vector for simpler memory managment.
Created a bigger example here: https://gist.github.com/KoKuToru/1d23af4bbf0b2bc89893
This is my Code
#ifndef INTLIST_H_INCLUDED
#define INTLIST_H_INCLUDED
#include <iostream>
using namespace std;
class intList
{
int upper_bound;
int arr[0];
public:
intList(){ arr[0] = 0; upper_bound = 0; }
void append(int x);
void sort();
friend ostream & operator << (ostream &, intList&);
inline int len(){ return upper_bound; }
inline int &operator [](int x){ return arr[x]; }
private:
void increment(int *a, int &l);
void swap(int &a, int &b);
};
void intList::swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void intList::increment(int *a, int &b)
{
b++;
a[b] = 0;
}
void intList::append(int num)
{
arr[upper_bound] = num;
increment(arr, upper_bound);
}
void intList::sort()
{
for(int i = 0; i < upper_bound; i++)
{
int minLoc = i;
for(int j = i+1; j<upper_bound; j++)
{
if(arr[j] < arr[minLoc])
minLoc = j;
}
if(minLoc != i)
swap(arr[i], arr[minLoc]);
}
}
ostream& operator << (ostream & dout, intList &a)
{
dout << "[ ";
for(int i = 0; i<a.upper_bound-1; i++)
dout << a.arr[i] << ", ";
dout << a.arr[a.upper_bound-1] << " ]";
return dout;
}
#endif // INTLIST_H_INCLUDED
The Code does its work perfectly fine. But at the end the Program Crashes. Giving some error like
process returned -1073741819 (0xC0000005) execution time : some seconds.
Just didn't get where am I going wrong.
This looks bad:
int arr[0];
First, C++ doesn't allow zero-sized fixed size arrays. Second, your code certainly needs more than a zero sized array.
Whatever use you make of this code is undefined behaviour (UB). UB includes code seemingly "working perfectly fine".
Your code has several problems.
For example, you have a fixed array of 0 size. If you want a dynamically growable array, you can use std::vector: you can add new items at the end of the vector (dynamically resizing it) using push_back() method:
#include <vector>
// Start with an empty vector
std::vector<int> v;
// Add some items to it
v.push_back(10);
v.push_back(20);
....
Note also that in header files it's not good to insert a using namespace std;. In this way you pollute the global namespace with STL classes, which is bad. Just use std:: prefix in header files.
Moreover, if you want to print the class content to an output stream, you may want to take the class as a const reference, since instances of the class are input parameters (you observe them and print their content to the stream):
std::ostream& operator<<(std::ostream& os, const IntList& a)
{
....
}
I have some trouble with class template inheritance and operators (operator +),
please have a look at these lines:
Base vector class (TVector.h):
template<class Real, int Size>
class TVector {
protected:
Real* values;
public:
...
virtual TVector<Real, Size>& operator=(const TVector<Real, Size>& rTVector) { //WORKS
int i = 0;
while (i<Size) {
*(values+i) = *(rTVector.values+i);
i++;
}
return *this;
}
virtual TVector<Real, Size> operator+(const TVector<Real, Size>& rTVector) const {
int i = 0;
Real* mem = (Real*)malloc(sizeof(Real)*Size);
memcpy(mem, values, Size);
while (i<Size) {
*(mem+i) += *(rTVector.values+i);
i++;
}
TVector<Real, Size> result = TVector<Real, Size>(mem);
free(mem);
return result;
}
};
2D vector class (TVector2.h):
template<class Real>
class TVector2: public TVector<Real, 2> {
public:
...
TVector2& operator=(const TVector2<Real>& rTVector) { //WORKS
return (TVector2&)(TVector<Real, 2>::operator=(rTVector));
}
TVector2 operator+(TVector2<Real>& rTVector) const { //ERROR
return (TVector2<Real>)(TVector<Real, 2>::operator+(rTVector));
}
};
Test (main.cpp):
int main(int argc, char** argv) {
TVector2<int> v = TVector2<int>();
v[0]=0;
v[1]=1;
TVector2<int> v1 = TVector2<int>();
v1.X() = 10;
v1.Y() = 15;
v = v + v1; //ERROR ON + OPERATOR
return 0;
}
Compilation error (VS2010):
Error 2 error C2440: 'cast de type' : cannot convert from
'TVector<Real,Size>' to 'TVector2' ...
What is wrong here ? is there a way to do this kind of stuff ?
Just looking for a way to not redefine all my Vectors classes.
I keep searching to do it, but I will be glad to get some help from you guys.
Sorry for bad English,
Best regards.
#include <memory>
using namespace std;
template<class Real, int Size> class TVector {
protected:
Real *_values;
public:
TVector() {
// allocate buffer
_values = new Real[Size];
}
TVector(Real *prValues) {
// check first
if (prValues == 0)
throw std::exception("prValues is null");
// allocate buffer
_values = new Real[Size];
// initialize buffer with values
for (unsigned int i(0U) ; i < Size ; ++i)
_values[i] = prValues[i];
}
// Do not forget copy ctor
TVector(TVector<Real, Size> const &rTVector) {
// allocate buffer
_values = new Real[Size];
// initialize with other vector
*this = rTVector;
}
virtual ~TVector() {
delete [] _values;
}
virtual Real &operator[](int iIndex) {
// check for requested index
if (iIndex < 0 || iIndex >= Size)
throw std::exception("requested index is out of bounds");
// index is correct. Return value
return *(_values+iIndex);
}
virtual TVector<Real, Size> &operator=(TVector<Real, Size> const &rTVector) {
// just copying values
for (unsigned int i(0U) ; i < Size ; ++i)
_values[i] = rTVector._values[i];
return *this;
}
virtual TVector<Real, Size> &operator+=(TVector<Real, Size> const &rTVector) {
for (unsigned int i(0U) ; i < Size ; ++i)
_values[i] += rTVector._values[i];
return *this;
}
virtual TVector<Real, Size> operator+(TVector<Real, Size> const &rTVector) {
TVector<Real, Size> tempVector(this->_values);
tempVector += rTVector;
return tempVector;
}
};
template<class Real> class TVector2: public TVector<Real, 2> {
public:
TVector2() {};
TVector2(Real *prValues): TVector(prValues) {}
TVector2 &operator=(TVector2<Real> const &rTVector) {
return static_cast<TVector2 &>(TVector<Real, 2>::operator=(rTVector));
}
TVector2 &operator+=(TVector2<Real> const &rTVector) {
return static_cast<TVector2 &>(TVector<Real, 2>::operator+=(rTVector));
}
TVector2 operator+(TVector2<Real> const &rTVector) {
return static_cast<TVector2 &>(TVector<Real, 2>::operator+(rTVector));
}
Real &X() { return _values[0]; }
Real &Y() { return _values[1]; }
};
int main(int argc, char** argv) {
TVector2<int> v = TVector2<int>();
v[0]=0;
v[1]=1;
TVector2<int> v1 = TVector2<int>();
v1.X() = 10;
v1.Y() = 15;
v = v1;
v += v1;
v = v + v1;
return 0;
}
Some misc notes:
it's very bad that you use malloc against of new. Real can be POD only to allow vector work well in your case. Use new or provide custom creation policy if you think that malloc provides better performance on PODs. Also do not forget to use delete [] instead of free while destroying memory buffer.
It's better to perform bounds checking while overloading operator[]
for better performance use ++i instead of postfix form. In former no temporary value is created.