简体   繁体   中英

Output (at most) 4 vector Elements in a Row

#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?

for (int i = 0; i < size; i++)
{
    cout << num[i];
    if ((i % 4) == 3)
        cout << endl;
    else
        cout << " ";
}
if ((size % 4) != 0)
    cout << endl;

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 )

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM