2017-12-08 9 views
0

パターンを保持しながらリスト要素の可能な限り多くの合計を数えるスクリプトがあります:higher-lower-higher-lower -higherなどC++エラー: '(std :: list <int>)(int&)'への呼び出しに一致しません

#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; 
} 

私は、リストの要素を比較しようとしていますどこただし、コンパイルの試みでそれはどこでもno match for call to '(std::list<int>) (int&)'をスローします。

私は間違っていますか?

+1

cmon people - なぜdownvote。 OPは完全なコードを提供しますが、少し不明瞭なエラーメッセージ(ただし、それを提供します)。さらに何を求めることができるか – pm100

答えて

0

a(n)は、ファンクションコールオペレータstd::list::operator()(int&)nと引数として呼び出すことを意味します。エラーno match for call to '(std::list<int>) (int&)'は、std::listにコールオペレータがないためです。

ランダムアクセス用にoperator[]を持つvectorとは異なり、リストはランダムアクセスをサポートしていません。ベクトルを使用すると、ベクトルaのランダムアクセス要素na[n]になります。

リストをトラバースするには、リストiteratorを使用します。 std::list::beginを使用して、イテレータを最初の要素に取得します。トラバースするには、代入、増分(++)、減分(--)の演算子を使用します。要素の値にアクセスするには、逆参照演算子(*)を使用します。

3

a(n)は無効です。 std::listには、呼び出し演算子(または使用することを想定した添え字演算子)がありません。 std::listはランダムアクセスを提供しません。

ランダムアクセスが必要な場合は、ランダムアクセスを提供するコンテナを使用してください(std::vectorなど)。次に、a[n]表記を使用してアイテムにアクセスできます。

+0

ベクトルを使用する場合は、 'remove'関数がないことも考慮する必要があります。 OPはインデックスで削除するために 'remove'を使用しようとしているようですが、[value](http://en.cppreference.com/w/cpp/container/list/remove)に基づいて削除します。代わりにイテレータで削除するために 'erase'を使うことができます(関連する[link](https://stackoverflow.com/questions/875103/how-do-i-erase-an-element-from-stdvector-by-index) )。パフォーマンスは、それぞれの消去呼び出しでベクトルの周りに要素をシフトさせるので、恐ろしいことになります。 –

+0

私たちは 'SO say 'を使う必要があります:: vector <>" 'tee shirt or mug – pm100

関連する問題