-3

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?

Ruli
  • 2,592
  • 12
  • 30
  • 40
mr-woot
  • 88
  • 1
  • 10

3 Answers3

4

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).

Jérôme
  • 8,016
  • 4
  • 29
  • 35
  • thanx for your help, that macros i use it for competetive programming purposes, but i will make sure it would not be there next time:P – mr-woot Nov 09 '15 at 11:01
  • 1
    @d_CoDE44 Do you have proof that your code is more competitive because of the macros? – juanchopanza Nov 09 '15 at 11:32
  • 1
    You solved my huge dilemma. I was confused a lot with this kinda behaviour. Because instead of using `vec[i] = val` i was doing `vec.push_back(val)` and the later one was adding 0's at the beginning of given size and then my value was printed. Btw thank you, man. – Safin Ghoghabori Nov 29 '21 at 14:11
3

You tell the vector to put 10 zeroes into itself. Then you push more values. Then you list the first 10. Of course you will only get the 10 zeroes out.

You are confusing reserving space to filling the vector.

Also, don't use macros and typedefs like this. The first time anyone else had to handle your code (like now) they will get a huge urge to spank you. It is totally unreadable, especially the _ macro.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
1

TL;DR: push_back is adding a new element at the end of your vector, so elements 10-19, it doesn't replace the zeros you put in it initially.

Seeker89
  • 282
  • 1
  • 2
  • 9