I'm doing an exercise of POO
but with pointers, and I have to insert an array into another in the position that is requested, without overwriting or losing those that are, just move it.
In the function void IntArr::addElement(int pos,int qtty,int *vec)
I do exactly that, but as you will see I complicate my life to do so.
Is not there a more efficient way to do it to avoid so many lines of code?
Some references:
-
qtty
is the number of elements I want to pass from the vector to be inserted. -
pos
is the position that I want to insert. -
vec
is the vector to insert -
p
dynamic vector where I will insert values -
used
number of used elements of the vector p -
size
vector size p
I leave the code of the functions, but if you need the full class and the main to understand what I need, tell me and I edit it.
This is my code :
void IntArr::addElement(int pos,int qtty,int *vec){
verificarPos(pos);
redimensionador(qtty);
//Iterador de los vectores auxiliares
int j=0;
//Vemos la cantidad de elementos a desplazar
int cantDesp;
cantDesp = used - pos;
//Creamos el vector auxiliar con la cantidad de elementos a desplazar
int vAux[cantDesp];
//Recorremos el array original para guardar los elementos a desplazar
for(int i=pos;i<used;i++){
//cout<<endl<<"vAux["<<j<<"] = "<<vAux[j]<<" --> p["<<i<<"] = "<<p[i]; //DEBUG
vAux[j] = p[i];
j++;
}
//Vemos hasta donde llegan los nuevos items a agregar
int espNew;
espNew = pos + qtty;
j=0; //Reinicio iterador
//Agregamos los nuevos items al vector p[]
for(int i=pos;i<espNew;i++){
p[i] = vec[j];
j++;
}
//Calculamos la pos hasta donde irán los items desplazados
int pAux;
pAux = used + qtty;
j=0; //Reinicio iterador
//Utilizamos el vAux para agregar los items salvados
for(int i=used-1;i<pAux;i++){
p[i] = vAux[j];
j++;
}
used += qtty;
}
//Verificador
void IntArr::redimensionador(int cant){
if(cant+used>size){
if(cant > 5){
size += cant;
}
else{
size += 5 + cant;
}
int *temp = new int [size];
memcpy (temp,p,used*sizeof(int));
delete [] p;
p = temp;
}
}
void IntArr::verificarPos(int &pos){
if(pos<=0){ //Si la posición es negativa o igual a cero
pos = 0;
}
else if(pos>=size){ //Si la posición supera el tamaño del array
pos = used;
}
}