I am making a hash table, in which each cell has several keys, what I have done is an object called cell in which the different keys of the table are stored as an array. Inside the table object, in turn, I have a vector of cells. The problem is that I have this code:
In the hash table object
#define Tablon
#include <vector>
template <class T >
class Tabla{
private:
std::vector<T> vCelda;
int size;
public:
Tabla(int n_celdas,int s_celda/*,int f_disp,int f_exp*/):
vCelda(n_celdas,celda(s_celda))
{
}
in the cell object
template <class T>
class celda{
private:
int nClaves;
T* claves;
int libres;
public:
celda(int nC ){
nClaves=nC;
claves = new T [nClaves];
libres=nClaves;
}
vCelda=new celda<T> [n_celdas] (s_celda) ;
When I compile it to see if it's ok it gives me the following error:
In file included from main.cpp:3:0:
tabla.hpp: In constructor ‘Tabla<T>::Tabla(int, int)’:
tabla.hpp:20:26: error: missing template arguments before ‘(’ token
vCelda(n_celdas,celda(s_celda))
If I put the following line:
vCelda(n_celdas,celda<T>(s_celda))
The following error is thrown:
In file included from main.cpp:3:0:
tabla.hpp: In instantiation of ‘Tabla<T>::Tabla(int, int) [with T = DNI]’:
main.cpp:39:37: required from here
tabla.hpp:20:38: error: no matching function for call to ‘std::vector<DNI, std::allocator<DNI> >::vector(int&, celda<DNI>)’
vCelda(n_celdas,celda<T>(s_celda))
^
I have tried removing the parameter in parentheses, but obviously it gives another error, since there is no empty default constructor. I'm wondering if C++ contains any predefined ways to perform these types of operations.
As the error says, you cannot use constructors with arguments in the
operator new[]
.You can use initialization between braces:
But this option is quite limited...it will only initialize the exact number of elements you specify... or use the literal value
0
. But of course, in that case, you could directly use the default constructor.Since you're using dynamic memory anyway, your best bet is to use a
std::vector< >
:You initialize it directly with the desired size, and as a second argument you pass it a reference
const
to the value you want to introduce, with which said value is copied to all the elements of thestd::vector< >
.