Vector resize

Why does vector resize cause array entries to be zeroed out?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


// It is NOT mandatory to use the provided template. You can handle the IO section differently.

int main() {
    /* The code required to enter n,k, candies is provided*/

    int N, K;
    cin >> N >> K;
    long long int temp;
    vector<long long int> numbers;
    numbers.resize(N);

    for (int i=0; i<N; i++){
        cin>>temp;
        cout<<"Temp is "<<temp<<endl;
        numbers.push_back(temp);        
    }
    for(int i=0;i<N;i++){
        cout<<numbers[i]<<endl;
    }
    cin.clear();

    long long int unfairness = 1000000;
    cout << unfairness << "\n";
    /** Write the solution code here. Compute the result, store in  the variable unfairness --
    and output it**/
    sort(numbers.begin(),numbers.end());
    for(int i=0;i<K;i++){
        cout<<numbers[i]<<endl;
    }
    
    for(int i=0; i<=N-K;i++){
       if((numbers[K+i-1]-numbers[i])<unfairness){
           unfairness=numbers[K+i-1]-numbers[i];
           cout << unfairness << "\n";
       }       
    }
    cout << unfairness << "\n";
    return 0;
}


If I comment/remove that line the contents of array is fine. What is wrong with using resize? When and how to use it?
There are two functions: resize() and reserve(). Read their descriptions.
resize is changing logical size of container. If new size is less than current, some elements are deleted, if it is larger, some element are created and value-initialized. For integers it is 0.

So after line 17 you have vector without any elements. After line 18 you have vector with N zeroes. After push_back you have N zeroes and one number pushed.

What are you trying to do with resize here?
Topic archived. No new replies allowed.