简体   繁体   中英

Why is the vector increasing its size to 10 when i am initialising its size to 5 and giving only 5 elements?

So i was doing this question on vector where i had to take input and then reverse all the elements

int main() {

    int i,n,a;   
    cin >> n;

    vector<int> arr(n);
    for(i=0;i<n;i++){
        cin >> a;
        arr.push_back(a);
    } 
    sort(arr.begin(),arr.end());
    for(i=0;i<n;i++){
        cout << arr[i] << " ";
    }
    return 0;
}

I wrote this code where i have mentioned the size as n of vector and pushing only n elements in it. But the output is coming out to be 0 0 0 0 0 for 5 elements. I guess that is because the vector has expanded its capacity to 10 and hence last 5 elements are printed which are obviously 0. Why is this happening?

vector<int> arr(n); creates a vector of size n from the start, all elements initialized to int{} aka zero. Then the loop adds n more elements via push_back .

vector<int> arr(n);

Since you claim that n = 5 , this line of code creates arr = {0, 0, 0, 0, 0}

But then you run a loop 5 times, and add 5 more elements to your vector via push_back :

for(i=0;i<n;i++){
    cin >> a;
    arr.push_back(a); // <-- mistake
}

And then you print the first 5 elements (which are 0) via

for(i=0;i<n;i++){
    cout << arr[i] << " ";
}

That is why, your output is 0 0 0 0 0 .

Solution:

You should add those elements to the space you already reserved for your vector:

Replace arr.push_back(a); with arr[i] = a;

Aside:

So i was doing this question on vector where i had to take input and then reverse all the elements

sort(arr.begin(),arr.end()); will not help you achieve this task.

You should use std::reverse :

reverse(arr.begin(), arr.end());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM