Output (at most) 4 vector Elements in a Row

82 views Asked by At
#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?

3

There are 3 answers

1
Captain Giraffe On

My entry to this competition is using a free function to your aid:

template <typename RAN_IT>
RAN_IT four_or_last(RAN_IT begin, RAN_IT end){
    for (RAN_IT it = begin; it != begin + 4; it++){
        if (it == end) 
            return end;
    }
    return begin + 4;
}

The loop can then be described as:

for (auto it = num.begin(); it != num.end(); /*inc in inner loop*/) {
    for (auto in = it; in != four_or_last(it, num.end()); in++) {
        std::cout << *in << " ";
    }
    it = four_or_last(it, num.end());
    std::cout << std::endl;
}
1
David Schwartz On
for (int i = 0; i < size; i++)
{
    cout << num[i];
    if ((i % 4) == 3)
        cout << endl;
    else
        cout << " ";
}
if ((size % 4) != 0)
    cout << endl;
0
aslg On

One solution could be,

for( int i = 0; i < size; ++i ) {
    int nextNumber = i + 1; // Just so you don't mix up the index
    if ( ( nextNumber % 4 ) == 0 ) {
        std::cout << num[ i ] << std::endl;
    }
    else {
        std::cout << num[ i ] << ' ';
    }
}

This allows you to easily change to other sizes by changing only one number. (ie, from 4 to 5, etc )