Okay after finishing the chapter about pointers and memory management, my book asks me to create a simple list class that holds strings, and supports bidirectional iterators. So far, this is what I came up with for the push_back function. I dynamically allocate a string array that is one larger than the the previous, and adds the next string to it.
I'm not sure if this is how I should be going about the problem however. Can I get the opinions of others to see if I'm on the right track before I dig a hole for myself?
Also, how do I deallocate str (so I just don't keep creating new arrays), and still be able to keep the values for the list?
Code:
class string_list{
private:
string* list; //points to the array of strings in the list
public:
string_list();
void push_back(string&);
};
void string_list::push_back(string s&){
element_count = element_count + 1;
string* str = new string[element_count];
if(element_count == 1){
str[0] = s;
list = str;
}
else{
::copy(list, list + (element_count - 1), str);
str[elemen_count - 1] = s;
list = str;
}
}