Reputation: 13
I have a piece of script to count the highest possible sum of list elements while retaining the pattern: higher-lower-higher-lower-higher etc.
#include <algorithm>
#include <stdio.h>
#include <list>
using namespace std;
int main() {
int n=0;
bool g = false;
int d = 1000000;
list<int> a(d,0);
int b;
for (int x=0; x<n; x++) { //load the list elements
scanf("%d", &b);
a.push_back(b);
}
for (int i=0; a(n) == a(n+1); i++) {
a.remove(n+1); //this is to remove any (consecutive) duplicates
}
if (a(n) > a(n+1)) {
g = false;
} else {
g = true;
}
while (n+1 < d) {
if (g) {
if (!(a(n) < a(n+1))) {
a.remove(n+1);
continue;
} else {
n = n+1;
g = !g;
continue;
}
} else {
if (!(a(n) > a(n+1))) {
a.remove(n+1);
} else {
n = n+1;
g = !g;
continue;
}
}
}
long long sum = 0 ;
for (int i = 0 ; i < a.count(); i++) {
sum += a(i);
}
printf("%lld ", sum);
return 0;
}
However, at compilation attempt it throws no match for call to '(std::list<int>) (int&)'
everywhere where I am trying to compare list elements.
What am I doing wrong?
Upvotes: 0
Views: 2219
Reputation: 926
a(n)
means calling the function call operator std::list::operator()(int&)
with n
as its argument. The error no match for call to '(std::list<int>) (int&)'
is because std::list
doesn't have a call operator.
A list does not support random access unlike a vector which have operator[]
for random access. Using a vector, the random access element n
of vector a
becomes a[n]
.
To traverse through a list, you use list iterators. Use std::list::begin
to get the iterator to first element. To traverse, use assignment, increment (++
) and decrement (--
) operators. To access the value of the element, use dereference operator (*
).
Upvotes: 0
Reputation: 30879
a(n)
is not valid. std::list
does not have a call operator (or a subscript operator, which is what I assume you intended to use). std::list
does not provide random access.
If you need random access, use a container that provides it, such as std::vector
. Then you can access items using a[n]
notation.
Upvotes: 3