C++ help/ Data structure Using the DynamicArray.cpp, extend it to include: * Rea
ID: 3855039 • Letter: C
Question
C++ help/ Data structure Using the DynamicArray.cpp, extend it to include: * Reading data strings from a file * Convert to generic array from integer based using templates or generics * Accommodate dynamic resizing using this algorithm: 1. Starting with a dynamic size of 10, if the number of elements exceed this number: a. Reallocate the container size to double the current size b. Move the contents of the current container to the newly sized container c. Delete the previously sized container. 2. Repeat from step 1a. as necessary. 3. Note the data file is called "words.txt". * Implement dynamic resizing using this algorithm: 1. Starting with a dynamic size of 10, if the number of elements exceed this number: a. Reallocate the container size to double the current size b. Move the contents of the current container to the newly sized container c. Delete the previously sized container. Resize C++ Data* ptemp = new Data[capacity*2 ]; for (int i=0; i<size; i++) ptemp[i] = _mdata[i]; delete [] _mdata; _mdata = ptemp; capacity *= 2; Resize Java data = Arrays.copyOf(data, capacity*2); capacity = capacity * 2;
Explanation / Answer
Here you go champ. I hope ypu will like the answer
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
template <typename Data>
class Demo {
public:
int capacity;
Data *_mdata;
int index;
Demo() {
capacity = 0;
index = 0;
_mdata = new Data[capacity];
}
void increase_capacity() {
Data* ptemp = new Data[capacity*2 ];
for (int i=0; i<index; i++)
ptemp[i] = _mdata[i];
delete [] _mdata;
_mdata = ptemp;
capacity *= 2;
}
void read(char* file_name) {
ifstream fin;
fin.open(file_name);
Data tmp;
while(fin >> tmp) {
if (index == capacity)
increase_capacity();
_mdata[index++] = tmp;
}
fin.close();
}
};
int main() {
Demo<string> demo;
cout << "Capacity was: " << demo.capacity <<endl;
demo.read("Words.txt");
cout << "Capacity is: " << demo.capacity <<endl;
}
Let me know if you need any changes to be made...
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.