#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
#include <conio.h>
using namespace std;
int main()
{
cout << "Enter the numbers: " << endl << "Write eof() when you want to end" << endl;
int x;
vector<int> num;
//enter numbers till eof() is encountered
while (cin >> x) {
num.push_back(x);
}
//sort the vector
sort(num.begin(), num.end());
//get size of the vector
typedef vector<double>::size_type vec_sz;
vec_sz size = num.size();
//loop to print 4 numbers according to size
for (auto i = 0; i < size; i++)
{
cout << num[i];
if (i == size - 1)
break;
i++;
cout << " " << num[i];
if (i == size - 1)
break;
i++;
cout << " " << num[i];
if (i == size - 1)
break;
i++;
cout << " " << num[i];
if (i == size - 1)
break;
cout << endl;
//<< " " << num[i + 1] << " " << num[i + 2] << " " << num[i + 3] <<
}
_getch();
return 0;
}
I want to print 4 numbers at a time of a vector of int's. When I tried to print the vector by doing i+=4 in the for loop, the compiler complained that 'i' was going over the size of the vector and the program crashed. Right now, what I have is works, but I find it really boring the way it's implemented right now and there must be a nice way to do it.
So my questions are -
1) How can I tidy up the code more?
2) When using a loop, how does the compiler access the memory in which vector contents are stored?
3) How to implement error checking so that the loop variable does not access elements beyond the vector size?
My entry to this competition is using a free function to your aid:
The loop can then be described as: