Question

In: Computer Science

Code in C++, create the erase function shown in int main() /* Use of dynamic memory...

Code in C++, create the erase function shown in int main()

/* Use of dynamic memory to implement dynamic array (like vector) */

#include <iostream>
using namespace std;

class MyVector {
private:
    int* arr; //only stores ints
    int size;
    int cap;
public:
    MyVector() : arr{nullptr} {}; // Default constructor;
    ~MyVector(); // Destructor: Cleans up stuff. Here deletes arr
    void push(int ele); // inserts element into vector
    friend ostream& operator <<(ostream& os, MyVector& v);
    
    
};


int main()
{
    MyVector vec;
    vec.push(1); //should store 1 in the vec
    vec.push(2); // should store 2 into the vec
    vec.push(10); // should print all elements
    vec.erase(0) // Erase element at position 0
    cout << vec << endl; // should print remaining elements
    
}

MyVector::~MyVector() // Destructor
{
    delete[] arr;
    cout << "Destroyed vector" << endl;
    
}

ostream& operator <<(ostream& os, MyVector& v)
{
    for(int i = 0; i < v.size; i++)
        os << v.arr[i] << " ";
    return os;
}

void MyVector::push(int ele)
{
    // Check if arr == nullptr. If yes, dynamically create an array of elements. Insert ele into array
    if (arr == nullptr) {
        cap = 2;
        arr = new int[cap];
        arr[0] = ele;
        size = 1;
    }
    else {
        // Check if there is space
        if (size < cap) {
            arr[size] = ele;
            size++;
        }
        else {
            int* temp = arr;
            arr = new int[2*cap];
            for (int i = 0; i < cap; i++)
                arr[i] = temp[i];
            delete[] temp;
            cap = 2*cap;
            arr[size] = ele;
            size++;
        }

    }
    
}

Solutions

Expert Solution

/* Use of dynamic memory to implement dynamic array (like vector) */

#include <iostream>

using namespace std;

class MyVector {
private:
    int *arr; //only stores ints
    int size;
    int cap;
public:
    MyVector() : arr{nullptr} {}; // Default constructor;
    ~MyVector(); // Destructor: Cleans up stuff. Here deletes arr
    void push(int ele); // inserts element into vector
    void erase(int index);
    friend ostream &operator<<(ostream &os, MyVector &v);

};


int main() {
    MyVector vec;
    vec.push(1); //should store 1 in the vec
    vec.push(2); // should store 2 into the vec
    vec.push(10); // should print all elements
    vec.erase(0); // Erase element at position 0
    cout << vec << endl; // should print remaining elements

}

MyVector::~MyVector() // Destructor
{
    delete[] arr;
    cout << "Destroyed vector" << endl;

}

ostream &operator<<(ostream &os, MyVector &v) {
    for (int i = 0; i < v.size; i++)
        os << v.arr[i] << " ";
    return os;
}

void MyVector::push(int ele) {
    // Check if arr == nullptr. If yes, dynamically create an array of elements. Insert ele into array
    if (arr == nullptr) {
        cap = 2;
        arr = new int[cap];
        arr[0] = ele;
        size = 1;
    } else {
        // Check if there is space
        if (size < cap) {
            arr[size] = ele;
            size++;
        } else {
            int *temp = arr;
            arr = new int[2 * cap];
            for (int i = 0; i < cap; i++)
                arr[i] = temp[i];
            delete[] temp;
            cap = 2 * cap;
            arr[size] = ele;
            size++;
        }

    }
}

void MyVector::erase(int index) {
    if (index < size) {
        for (int i = index; i < size-1; ++i) {
            arr[i] = arr[i+1];
        }
        size--;
    }
}

Related Solutions

convert following C++ code into MIPS assembly: int main() {                                 &
convert following C++ code into MIPS assembly: int main() {                                         int x[10], occur, count = 0;                                                              cout << "Type in array numbers:" << endl; for (int i=0; i<10; i++) // reading in integers                               { cin >> x[i];        } cout << "Type in occurrence value:" << endl;                                 cin >> occur;                                                 // Finding and printing out occurrence indexes in the array                                  cout << "Occurrences indices are:" <<...
C CODE PLZ! All instructions for what to do in code #include <stdio.h> int main(int argc,...
C CODE PLZ! All instructions for what to do in code #include <stdio.h> int main(int argc, char **argv) { int n, k, l, r, t, d, i; char str[65]; /* Make the user enter a non-negative integer */ printf("Please enter a non-negative integer: "); scanf("%d", &n); while (n < 0) { printf("Sorry, your input is incorrect.\n"); printf("Please enter a non-negative integer: "); scanf("%d", &n); } /* Convert the integer to reversed binary: e.g. 6 gets converted to 011 */ if...
Translate the following function f to MIPS assembly code. int f(int a, int b, int c,...
Translate the following function f to MIPS assembly code. int f(int a, int b, int c, int d) { return func(func(a,b), func(b+c,d)); } Assume the followings. • The prototype of function func is “int func(int a, int b);”. • You do not need to implement function func. The first instruction in function func is labeled “FUNC”. • In the implementation of function f, if you need to use registers $t0 through $t7, use the lower-numbered registers first. • In the...
CODE IN JAVA Create a new class named Task1. In its main function, use Scanner to...
CODE IN JAVA Create a new class named Task1. In its main function, use Scanner to read integers from the keyboard with the method nextInt. Use a try catch block to capture non-integer input, and tell the user, "This is not an Integer". The program loop should end when the user enters the string "quit". (Hint: "quit" is clearly not a number and will be captured in the try / catch block.) A typical Output Dialog is shown below: Enter...
Consider the following C code that outlines Fibonacci function int fib (int n) { if (n...
Consider the following C code that outlines Fibonacci function int fib (int n) { if (n == 0) return 0; else if (n==1) return 1; else return fib(n-1) + fib (n-2); } For this programming assignment, write and test an ARMv8 program to find Fibonacci (n). You need to write a main function that calls the recursive fib function and passes an argument n. The function fib calls itself (recursively) twice to compute fib(n-1) and fib (n-2). The input to...
C PROGRAMMING Create the int delete(int key) function so that it deletes the LAST occurrence of...
C PROGRAMMING Create the int delete(int key) function so that it deletes the LAST occurrence of a given number in the linked list Make sure the parameter for this delete function is (int key). Also, use these variables and global Nodes BELOW as this is a DOUBLY LINKED LIST!!! #include #include typedef struct node {             int data;             struct node *next;             struct node *prev; } Node; Node *head; Node *tail; ----------------------- So, the function has to look like...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g,...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords)] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) setup_game() does exactly what the name suggests. It sets up a new game of hangman. This means that it picks a random word from the supplied wordlist array and puts that into g->hidden_word. It sets...
1. Convert the following code shown below to C++ code: public class HighwayBillboard { public int...
1. Convert the following code shown below to C++ code: public class HighwayBillboard { public int maxRevenue(int[] billboard, int[] revenue, int distance, int milesRes) { int[] MR = new int[distance + 1]; //Next billboard which can be used will start from index 0 in billboard[] int nextBillBoard = 0; //example if milesRes = 5 miles then any 2 bill boards has to be more than //5 miles away so actually we can put at 6th mile so we can add...
3. Translate the following C code to MIPS assembly code (in two separate files). int main()...
3. Translate the following C code to MIPS assembly code (in two separate files). int main() { printf(“before subroutine!\n”); Subfunc(); printf(“after subroutine!\n!”); } void Subfunc() {printf(“I am subroutine!\n”);} Submission file: Lab4_3a.asm for the main routine and Lab4_3b.asm for the sub-routine.
3. Translate the following C code to MIPS assembly code (in two separate files). int main()...
3. Translate the following C code to MIPS assembly code (in two separate files). int main() { printf(“before subroutine!\n”); Subfunc(); printf(“after subroutine!\n!”); } void Subfunc() {printf(“I am subroutine!\n”);} 4. Translate the following C code to MIPS assembly (in two separate files). Run the program step by step and observe the order of instructions being executed and the value of $sp. int main() { int x=2; z=Subfunc(x); printf(“Value of z is: %d”, z); } int Subfunc(int x) { return x+1;}
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT