here's an example program that creates a vector of user-given size M using the new operator:
#include <vector>
// 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:
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