0

Why it's showing an error in incrementing vector elements by using ++ or -- operator?

#include <bits/stdc++.h>
using namespace std;
int main(){
    vector<int> a[1000];

    for(int i=0;i<1000;i++){
        a[i]++;
        a[1000-i-1]--;
    }

    return 0;
}
Sachin
  • 1
  • 7
    `vector a[1000];` is making an array of vectors, not a vector with 1000 elements. `a[i]++` would be trying to increment one of those thousand vectors, not just a single value – dwcanillas Jul 14 '21 at 05:06
  • 1
    `vector a(1000);` seems like what you want. Declare a vector of size 1000. – Retired Ninja Jul 14 '21 at 05:26

3 Answers3

1

From a comment: vector<int> a[1000]; is making an array of vectors, not a vector with 1000 elements. a[i]++ would be trying to increment one of those thousand vectors, not just a single value.

Once you fix the error in the declaration, there’s no problem with incrementing or decrementing an element like that.

Sneftel
  • 40,271
  • 12
  • 71
  • 104
  • +1 because this comes closest to answering the question, which is about what causes the error. The other answers are correct, but point out why the assumed expectation of the OP is not aligned with the results of the code. – dmedine Jul 14 '21 at 06:03
1

Syntax you used is for creating array of vectors not a vector with size 1000. vector<int> a[1000]; means

a is the array of vectors of int of size 1000

Array of Vectors:

vector <data_type> V[size];

Vector Of size n:

vector<int> V(size);
Suryansh Singh
  • 1,123
  • 7
  • 15
1

As Sneftel explained the problem, to resolve this, you can do this

    vector<int> a(1000, 0); // vector(number_elements, default_value)

This will make 1000 ints with 0 values. Rest of your code will work fine.

foragerDev
  • 1,307
  • 1
  • 9
  • 22