Raghav Sharma
Raghav Sharma

Reputation: 140

vector <pair<int,int>>v(size); showing 0 as values when printed

C++: vector<pair<int,int>>v(size); showing 0 as values when I am trying to print out the values, but when the vector size is not declared it is showing correct output? Why so? For example:

int x;
cin>>x;
vector<pair<int,int>>v(x); //Size declared.
for(int i=0;i<x;i++){
    int p,q;
    cin>>p>>q;
    v.push_back(make_pair(p,q));
}

But when I am trying to print the values, it is printing 0 only.

I/P->  
3
1 2
3 4
5 6
O/P->
0 0
0 0
0 0

But when I don't declare the size of the vector it prints the output without any error, why is that? i.e

int x;
cin>>x;
vector<pair<int,int>>v; //Size is not declared.
for(int i=0;i<x;i++){
    int p,q;
    cin>>p>>q;
    v.push_back(make_pair(p,q));
}
I/P->  
3
1 2
3 4
5 6
O/P-> 
1 2
3 4
5 6

It shows the correct output. Why is that?

Upvotes: 2

Views: 948

Answers (2)

Aconcagua
Aconcagua

Reputation: 25536

It is because the vector's constructor accepting an integral (it is of type size_t) does not only provide sufficient size, but creates x default objects. You then append your new objects to these default ones.

Be aware that the term 'size' in STL wording refers to the number of elements already inserted/contained, the total number of elements that can be held without re-allocation is referred to as 'capacity'.

If you want to pre-allocate sufficent capacity without creating new objects, you need to use reserve:

std::vector<std::pair<int,int>> v;
v.reserve(x);

Upvotes: 3

Nick
Nick

Reputation: 10539

Vector constructor with int means it create that many elements. They are pairs of zeroes. Then you push back and it creates new elements at the end. So all elements are X * 2.

I am assuming then you do not check the size, but instead you list first X elements.

You can fix by either vector::reserve(x) or by using []instead of pushing back. Then operation will look more like array access.

Because element is pair of int, both options are good.

Reserve is faster, array like access is more generic.

Upvotes: 1

Related Questions