So I was given this array:
int arr[] = {60,70,30,15,17,80,16,75,90,85,40,75};
I have to "fit" as much elements in this array as possible while having their sum being less than 500 (basically removing the biggest one until sum is less than 500).
This is what i've tried:
#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
int largestOfArray(int number[]);
int main()
{
int sum = 0;
int i = 0;
int arr[] = {60,70,30,15,17,80,16,75,90,85,40,75};
list<int> ar(arr,arr+12);
for (i = 0; i < 12;i++)
sum += arr[i];
while (sum > 500)
ar.remove(largestOfArray(arr[12]));
for (i = 0; i < 12;i++)
sum += arr[i];
for (i = 0;i < 12; i++)
cout << arr[i];
cout << sum;
return 0;
}
int largestOfArray(int number[12]){
int i = 0;
int largest = number[0];
for (i = 0;i < 12;i++){
if (largest < number[i]) largest = number[i];
}
return largest;
}
I keep getting this error:
no match for 'operator[]' (operand types are 'std::__cxx11::list' and 'int')
I know it has something to do with the ar.remove(largestOfArray(ar[12]));
but i dont know how to fix it.
Firstly, you use both ar and arr, while arr is an array and ar is a list. This is both confusing to the reader and (it turns out) to the code author.
In C++, std::list doesn't have random access. You cannot use ar[], since operator[] is not defined for lists. Further, largestOfArray expects an array, not a list. You probably intended to use arr there instead of ar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With