I created a template class vect that allows me to create arrays of elements of type T, access them from 1 to n (instead of 0 to n-1) and permute them (I have to permute them that way instead of permuting them the classical way).
Here's the header file:
#ifndef VECT_HPP
#define VECT_HPP
#include <vector>
template <class T>
class vect
{
public:
vect(int=0);
~vect();
void show(void) const;
void permute(int,int);
T& operator[](int);
const T& operator[](int) const;
void init_perm(void);
private:
int n;
double* p;
std::vector<int> s;
};
#endif /* GUARD_VECT_HPP */
#include "vect.cpp"
and here's the source file:
#ifndef VECT_CPP
#define VECT_CPP
#include "vect.hpp"
#include <iostream>
using namespace std;
template <class T>
vect<T>::vect(int a): n(a)
{
p=new double[n];
s.resize(n);
init_perm();
}
template <class T>
vect<T>::~vect()
{
delete [] p;
}
template <class T>
void vect<T>::show(void) const
{
for (int i = 0; i < n; i++)
cout << p[i] << endl;
}
template <class T>
void vect<T>::permute(int a,int b)
{
static int c;
a--;
b--;
c=s[a];
s[a]=s[b];
s[b]=c;
}
template <class T>
T& vect<T>::operator[](int i)
{
return p[s[i-1]-1];
}
template <class T>
const T& vect<T>::operator[](int i) const
{
return p[s[i-1]-1];
}
template <class T>
void vect<T>::init_perm(void)
{
for (int i = 0; i < n; i++)
s[i]=i+1;
}
#endif
and here's the file main.cpp that I uesd to test the class:
#include "vect.hpp"
#include <iostream>
using namespace std;
int main(void)
{
vect<int> v(5);
v.show();
for (int i = 1; i <=5; i++)
v[i]=10*i;
v.show();
cout << "Permuted 3 and 5" << endl;
v.permute(3,5);
v.show();
v.init_perm();
cout << "Initialized permutations" << endl;
v.show();
return 0;
}
I get the following error:
In file included from vect.hpp:25:0,
from main.cpp:1:
vect.cpp: In instantiation of ‘T& vect<T>::operator[](int) [with T = int]’:
main.cpp:11:6: required from here
vect.cpp:43:19: error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
return p[s[i-1]-1];
I searched on Internet about this error and how it can be caused by a bad implementation of operator[]
, but after correction I still have the same error, even when I return p[i-1]
instead of p[s[i-1]]
.
Could you please help me?