In many applications, the order of the data items in a list changes over time. N
ID: 3766600 • Letter: I
Question
In many applications, the order of the data items in a list changes over time. Not only are new data items added and existing ones removed, but data items are repositioned within the list. The following function named toTop is needed to move a data item to the beginning of an array. The toTop function should be a void function that accepts a value as a parameter in the function parentheses. Do not use a vector for this assignment.
Create a class that has an array as a private data member. You cannot use a vector for this assignment (5 points).
You must include a function to fulfill the precondition and postcondition listed above. This must be a void function with a parameter.
Include a class function to add elements to the array
You will also need a client program that creates an object of your class and calls the function(s) you created to meet the requirements of this project
Explanation / Answer
#include <iostream>
using namespace std;
class UsingArrays {
private:
int* arr;
int size;
int maxCapacity;
public:
UsingArrays();
void addElement(int element);
int getSize();
void toTop(int element);
void printArray();
};
UsingArrays::UsingArrays(void) {
arr = new int[5];
size = 0;
maxCapacity = 5;
}
void UsingArrays::printArray() {
for (int i = 0; i < getSize(); i++) {
cout << arr[i] << endl;
}
}
int UsingArrays::getSize() {
return size;
}
void UsingArrays::addElement(int element) {
if (getSize() >= maxCapacity) {
maxCapacity *= 2;
int* newArr = new int[maxCapacity];
copy(arr, arr + getSize(), newArr);
delete[] arr;
arr = newArr;
}
arr[size] = element;
size++;
}
void UsingArrays::toTop(int element) {
if (getSize() != 0) {
if (getSize() >= maxCapacity) {
maxCapacity *= 2;
int* newArr = new int[maxCapacity];
copy(arr, arr + getSize(), newArr);
delete[] arr;
arr = newArr;
}
for (int i = 0; i < size; i++) {
int temp = arr[i];
arr[i] = element;
element = temp;
}
arr[size++] = element;
}
}
int main() {
UsingArrays testObject;
testObject.addElement(1);
testObject.addElement(2);
testObject.addElement(3);
testObject.addElement(4);
testObject.addElement(5);
testObject.addElement(6);
testObject.printArray();
testObject.toTop(0);
testObject.printArray();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.