Untitled
unknown
plain_text
2 years ago
3.2 kB
63
Indexable
#include <iostream> #include <cstring> using namespace std; class Word { private: char *chars; public: explicit Word(const char *input = "UNDEFINED") { chars = new char [strlen(input)+1]; strcpy(chars, input); } Word(const Word &_word) { if (_word.chars != nullptr) { chars = new char [strlen(_word.chars)+1]; strcpy(chars, _word.chars); } } ~Word() { delete [] chars; } Word& operator =(const Word &other) { if (&other != this) { delete [] chars; chars = new char[strlen(other.chars)+1]; strcpy(chars, other.chars); } return *this; } const char *getChars() const { return chars; } }; class Sentence { private: Word *words; int capacity; int numWords; public: Sentence(int _capacity = 10) { words = new Word[_capacity]; capacity = _capacity; numWords = 0; } Sentence& operator =(Sentence const &other) { if (&other != this) { delete [] words; //free current memory words = new Word[other.capacity]; //reserve memory for (int i = 0; i < other.numWords; i++) { words[i] = other.words[i]; } //potential infinite recursive call? capacity = other.capacity; numWords = other.numWords; } return *this; } void add(const Word &input) { if (numWords < capacity-1) { words[numWords] = input; ++numWords; } else { Word *tmp = new Word[capacity]; //reserve memory for (int i = 0; i < numWords; i++) { tmp[i] = words[i]; } //assign delete [] words; //free capacity += 11; words = new Word[capacity]; //reserve larger memory space for (int i = 0; i < numWords; i++) { words[i] = tmp[i]; } //reassign previous values delete [] tmp; words[numWords] = input; //add new word ++numWords; //I swear the error is in this method somewhere but I'm going crazy looking at this } } void print() const { for (int i = 0; i < numWords-2; i++) { cout << words[i].getChars() << " "; } cout << words[numWords-1].getChars() << endl; } ~Sentence() { delete [] words; } void swap(int index1, int index2) { Word tmp = words[index1]; words[index1] = words[index2]; words[index2] = tmp; } }; int main() { int n; cin >> n; cin.get(); cout << "CONSTRUCTOR" << endl; Sentence s; cout << "ADD WORD" << endl; for (int i = 0; i < n; ++i) { char w[100]; cin.getline(w, 100); Word word(w); s.add(word); } cout << "PRINT SENTENCE" << endl; s.print(); cout << "COPY" << endl; Sentence x = s; cout << "SwAP" << endl; x.swap(n / 2, n / 3); x.print(); cout << "ORIGINAL" << endl; s.print(); return 0; }
Editor is loading...