push_back
doesn't add the value of i
to the vector n
in the following code:
#include <bits/stdc++.h>
#define _ ios::sync_with_stdio(0);cin.tie(0);
using namespace std;
/*macros*/
#define fi(i,a,b) for(int i=a;i<b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
#define pb push_back
#define min(a,b) ((a<b)?a:b)
#define max(a,b) ((a<b)?b:a)
/*data types*/
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vii;
typedef vector<ll> vll;
typedef set<int> si;
typedef set<ll> sll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
int main()
{ _
vi n(10);
fi(i,0,10)
{
n.push_back(i);
}
fi(i,0,10)
cout << n[i] << endl;
return 0;
}
Output:
0
0
0
0
0
0
0
0
0
0
I have looked other resources from topcoder tutorial and other questions on stackoverflow. I know that vector<int> n(10)
initializes 10 indexed vector
to 0 by default, but why the above code is not putting the push_back
values back to vector and updating the vector?
Your first statement: vi n(10);
Initialize your vector with 10 int
.
When you are using push_back
you are actually adding value to your vector (index 10 to 19). After the first loop you have 20 elements in your vector. So, your second loop is only displaying the 10 first elements.
Instead do the following: n[i] = i;
in your first for
loop
Btw, you shouldn't use tydedef
and macro like you do, this is very confusing (and bad practise).