Ask coding questions

← Back to all posts
Using vector
DarkHollow (0)

#include <iostream>
#include <vector>
using namespace std;
void populate(vector<int>, int);
int getMax(vector<int>);
int main()
{
vector<int> arr(20);
int max;
populate(arr, 20);
int size = arr.size();
max = getMax(arr);
cout << "Max: " << max << endl;
}
void populate(vector<int> arr, int)
{
cout << "Enter 20 values: ";
for (int count = 0; count < 20; count++) {
cin >> arr[count];
cout << arr[count];
}
}
int getMax(vector<int> arr)
{
int max = arr[0];
int size = arr.size();
for (int i = 0; i < size; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}

Answered by mwilki7 (287) [earned 5 cycles]
View Answer
Commentshotnewtop
mwilki7 (287)

Your maximum function is correct.
It's just your populate function just copies vector<int> arr back in main and only changes the copy instead of the original.

To fix this, either:
• pass by reference (the easier way):
change

void populate(vector<int> arr, int)

to

void populate(vector<int> &arr, int)

OR

• return a new vector (still easy, just a different return type)

int main()
{
    ...
    ...
    vector<int> arr = populate(20);
    ...
}
vector<int> populate(int)
{
    vector<int> arr;
    ...
    ...
    return arr;
}
ash15khng (393)

1) post into repl
2) what's the problem

DarkHollow (0)

I want to get the max value using vector. The void function is working correctly that what I think. However, when I am trying to get the max value using int function, it is giving the value of 0. It's vect instead of arr. I don't know what I am missing. Thank you! @ash15khng