I have been programming a little program in C++ with VisualStudio and while I didn't find a nice way to find an element of an array, I just made my own function to get the biggest value out of an array. But I couldn't do that either because the size() function doesn't work there.
I used size in the int main()
and it works fine but in my function int biggest_num(int tmp_array[])
it wouldn't work because it says no instance of overloaded function matches the argument list
. I tried do initialize the variable before but it still doesn't work.
#include <iterator>
int biggest_num(int tmp_array[] = {}) {
int q = 0;
int array[] = tmp_array; // Error: C++ initialization with '{...}' expected for aggregate object
for (int i = 0; i < size(array); i++) q = (q < array[i]) ? q : array[i]; //size(array) Error: <error-type>
return q;
}
int main(){
int nums[] = {23, 34, 6, 2, 3, 456, 32, 76, 24, 7, 9, 47};
cout << biggest_num(nums) << endl;
}
Without initialization:
#include <iterator>
int biggest_num(int tmp_array[]){
int q = 0;
for (int i = 0; i < size(tmp_array); i++) q = (q < tmp_array[i]) ? q : tmp_array[i]; // size() Error: no instance of overloaded function matches the argument list
return q;
}
int main(){
int nums[] = {23, 34, 6, 2, 3, 456, 32, 76, 24, 7, 9, 47};
cout << biggest_num(nums) << endl;
}
SOLUTION:
#include <iostream>
using namespace std;
int biggest_num(const int tmp_array[], size_t n)
{
int q = tmp_array[0];
for (size_t i = 1; i < n; i++)
{
if (q < tmp_array[i]) q = tmp_array[i];
}
return q;
}
int main() {
char yn = ' ';
int nums[] = { 1, 2, 3 };
cout << biggest_num(nums, size(nums)) << endl;
}