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;
}
3 Answers
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.
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);
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.