This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Wednesday, March 15, 2023

Write a function that creates a vector of user-given size M using new operator in a program

  here's an example program that creates a vector of user-given size M using the new operator:

#include <iostream>
#include <vector>
using namespace std;

// Function to create a vector of given size using new operator
vector<int>* createVector(int size) {
    return new vector<int>(size);
}

int main() {
    int M;

    cout << "Enter the size of vector: ";
    cin >> M;

    // Create vector using new operator
    vector<int>* myVector = createVector(M);

    // Display vector size
    cout << "Vector size: " << myVector->size() << endl;

    // Deallocate memory used by vector
    delete myVector;
    return 0;
}

In this program, we define a function called createVector that takes an integer argument size and returns a pointer to a new std::vector<int> object created using the new operator with the specified size.

In the main function, we prompt the user to enter the size of the vector, and then call the createVector function to create a new vector of the given size. We then display the size of the vector using the size() method of the vector object. Finally, we deallocate the memory used by the vector using the delete operator to avoid memory leaks.

Here's an example output of the program:

Enter the size of vector: 5
Vector size: 5

As we can see, the program successfully creates a vector of the given size using the new operator.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget