У меня есть простой проект телефонной книги на c ++, и я не могу использовать std :: vector.Поэтому я решил создать его для себя.И я хотел бы попросить небольшую помощь о моей функции push_back.
Так что это в vector.h:
class Vector{
int siz; //size
std::string* elem; //elements
public:
Vector(): siz(0){}
int getSize()const;
void pushBack(std::string const&);
std::string operator[](int) const;
Vector& operator=(const Vector&);
};
И это моя функция push_back:
void Vector::pushBack(std::string const& s){
std::string* temp = new std::string[siz + 1];
for(int i = 0; i < siz; i++)
temp[i] = elem[i];
temp[siz] = s;
// delete[] elem; // The debugger points here
this->elem = temp;
this->siz += 1;
}
Здесь я использую функцию push_back:
const Vector read(){
Vector v;
std::ifstream file;
file.open("data.txt", std::ios::in);
int db = 10 * linecounter();
std::string temp;
for(int i = 0; i < db; i++)
{
if(i % 10 == 9 && i != 0){
getline(file, temp); // the last data in the line after that ther is a \n
v.pushBack(temp);
}
else{
getline(file, temp, ';'); // read in the temp till the ;
v.pushBack(temp); // The debugger points here
}
}
return v;
}
И моя проблема в том, что когда я не использую delete[] elem;
Это приведет к некоторой утечке памяти.Когда я использую, программа сразу падает.