2

I wanted to add elements in vector, not complicated at all.

#include <iostream>
#include <vector>

int main(){
    int n;
    std::cin>>n;
    std::vector<int> arr(n);
    for(int i=0;i<n;i++){
        arr.push_back(i);
    }
    for(int i=0;i<n;i++){
       std::cout<<arr[i];
    }
    std::cout<<"\n";
    std::cout<<arr.capacity()<<"\n";
    std::cout<<arr.size()<<"\n";


 }

But the problem is when I compile the size and capacity are 2 times bigger than the size i put in code(in this case size is n), and n zeros are printed out.

Ste1Drag
  • 49
  • 1
  • 8

1 Answers1

3

push_back always appends new elements onto the end of a vector.

std::vector<int> arr(n); sets the initial size to n.

Hence you end up with more than n elements.

Using simply std::vector<int> arr; is a good fix - only worry about reallocation issues if your performance profiler highlights it as a bottleneck.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    "_only worry about reallocation issues if your performance profiler highlights it as a bottleneck._" Which `arr.reserve (n)` might help to fix :) EDIT: Had `reserve` in mind, while my hands wrote `resize`.. Derp.. :/ – Algirdas Preidžius Oct 02 '19 at 13:11
  • 2
    @Paul92: I disagree with that. If I had a dollar for every bit of UB I've come across due to a misplaced `arr[i]` I'd be very, very rich. I like the simplicity of not having to worry about how many things I've put into the vector. – Bathsheba Oct 02 '19 at 13:12
  • @Paul92 I aggree with Bathsheba, if you want to avoid reallocation, either use `arr.reserve` and `arr.push_back` or at least use `arr.at(i)=...` as that is bounds checked. – eike Oct 02 '19 at 13:14
  • 2
    If you're *really* worried then `reserve` and `emplace_back` are hard to beat. But with such a light payload as an `int`, this is hardly pertinent. – Bathsheba Oct 02 '19 at 13:15
  • Yes, but i somehow expected when I insert size, without adding elements to vector, I expected the size to be zero and capacity to be `n` , but size and capacity are zero, so that's what confuses me. – Ste1Drag Oct 02 '19 at 13:20
  • 1
    @user700999: That's exactly how Java does it, but in the C++ world we're more grown up than that. – Bathsheba Oct 02 '19 at 13:23