I wrote a code to sort a vector of Integer and noticed that one version is working fine and another one isn't.
Version 1: Using vector.reserve
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
ios_base::sync_with_stdio(false);
vector<int> a;
a.reserve(4);
int i = 0;
while (i < 4)
{
cin >> a[i++];
}
sort(a.begin(), a.end());
for (int i :a)
{
cout << i << " ";
}
}
INPUT: 1 5 3 2
OUTPUT:
Version 2: Defining vector size in advance
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
ios_base::sync_with_stdio(false);
vector<int> a(4);
int i = 0;
while (i < 4)
{
cin >> a[i++];
}
sort(a.begin(), a.end());
for (int i :a)
{
cout << i << " ";
}
}
INPUT: 1 5 3 2
OUTPUT: 1 2 3 5
I am not quite sure what are the differences between two and when to use which if there is some distinction.