After java I study C ++, slowly I understand the removal of objects and pointers. Trying to write my ArrayList in cpp. When the internal array is filled, a new array is created, the data is added there, and then I clear the memory and transfer the pointer to the new array.
#include "ArrayList.h" #include <iostream> ArrayList::ArrayList() { lenght=0; sizeArr=10; values= new char[sizeArr];// } bool ArrayList::checkIndex(int index){ if(index<0 || index>lenght-1){ throw index; return false; } return true; } char* ArrayList::copyarray(char *src,int len, int newlenght){ char* newArr=new char[newlenght]; for(int i=0;i<len;i++){ newArr[i]=src[i]; } delete [] src; src=nullptr; src=newArr; return src; } char ArrayList::get(int index){ checkIndex(index); return values[index]; } void ArrayList::remove(int){ } int ArrayList::indexOf(const char* val){ return 0; } void ArrayList::add(const char* val){ values[lenght]=val; lenght++; if(lenght==sizeArr){ sizeArr=(sizeArr*2)-(sizeArr/2); copyarray(values,lenght,sizeArr); } } int ArrayList::size(){ return lenght; } bool ArrayList::isEmpty(){ return lenght==0; } bool ArrayList::conteins(const char* val){ return indexOf(val)!=-1; } int ArrayList::hashCode(){ return 1; } ArrayList::~ArrayList() { //delete values; } main method:
ArrayList list; list.add("hello"); list.add("hello1"); list.add("hello2"); list.add("hello3"); list.add("hello"); list.add("hello1"); list.add("hello2"); list.add("hello3"); list.add("hello"); list.add("hello1"); list.add("hello2"); list.add("hello3"); list.add("hello"); list.add("hello1"); list.add("hello2"); list.add("hello3"); for(int i=0;i<list.size();i++) cout<<list.get(i)<<endl If I do not delete the old array in the copyarray method, then everything is displayed normally, and if I delete, then some added values and some garbage are output.