输出(最多)一行中的4个向量元素

时间:2015-06-16 17:24:14

标签: c++ loops memory vector compiler-optimization

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

我想在int的向量时打印4个数字。当我试图通过在for循环中执行i + = 4来打印向量时,编译器抱怨'我'超过了向量的大小并且程序崩溃了。 现在,我所拥有的是有效的,但我觉得它现在的实施方式真的很无聊,必须有一个很好的方法。

所以我的问题是 -

1)我如何更多地整理代码?

2)当使用循环时,编译器如何访问存储矢量内容的存储器?

3)如何实现错误检查,以便循环变量不访问超出向量大小的元素?

3 个答案:

答案 0 :(得分:2)

Multiple types were found that match the controller named 'Header'.

答案 1 :(得分:0)

一种解决方案可能是,

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

这使您可以通过仅更改一个数字轻松更改为其他尺寸。 (即4到5等)

答案 2 :(得分:0)

我参加本次比赛是为了帮助您使用免费功能:

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

然后可以将循环描述为:

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