Reputation: 765
I'm getting a little stuck changing functions to use vectors. I've got the below function that creates a new dynamic array. Now I need to do the same but use vectors.
int *makeData(int size)
{
int *ptr = nullptr;
ptr = new int[size];
return ptr;
}
This is all i got so far and can't seem to figure out what to do next. Do i need a pointer to return?
int *makeData(int size)
{
vector<int> data(100);
}
This function seems to be okay but is there a way to optimize it (make it simpler, and cleaner).
void getMovieData2(vector<int> data, int num)
{
int temp;
cout << "Enter the number of movies each student saw.\n";
for (int count = 0; count < num; count++)
{
cout << "Student " << (count + 1) << ": ";
cin >> temp;
data.push_back (temp);
while (arr[count] <= 0)
{
cout << "The number of movies be greater than zero.\n";
cout << "How many movies were seen by Student "
<< (count + 1) << "? ";
cin >> temp;
data.push_back (temp);
}
}
}
Upvotes: 1
Views: 103
Reputation: 5135
Your makeData
for vectors would be
vector<int> makeData(int size) {
return vector<int>(size);
}
As you see it is effectively the same as
vector<int> data(size);
However it can be useful if you use auto consistently
auto data = makeData(size);
As of your getMovieData
function: no, that function is not working as expected. You are passing a vector as value and are "returning" data in it - except that you are putting your data into a local copy that will be destroyed when the function returns.
The solution is to use a reference, as in
void getMovieData(vector<int> &outData, int count);
However I suggest you simply return a new vector
vector<int> getMovieData(int count);
Upvotes: 5
Reputation: 71989
Using a vector has made the makeData
function redundant. It doesn't do anything that simply declaring a variable of type vector doesn't already do better.
Cleaning up the other function is possible, but has nothing to do with the question about vectors.
Also, none of this has anything to do with overloading.
Upvotes: 6