c++ - 连续输出(最多)4 个 vector 元素

标签 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 vector 的 4 个数字。当我试图通过在 for 循环中执行 i+=4 来打印 vector 时,编译器提示说“i”超出了 vector 的大小并且程序崩溃了。 现在,我所拥有的是有效的,但我发现它现在的实现方式真的很无聊,必须有一个很好的方法来做到这一点。

所以我的问题是 -

1)如何让代码更整洁?

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

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

最佳答案

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

关于c++ - 连续输出(最多)4 个 vector 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30874208/

相关文章:

loops - 奇怪的嵌套循环的时间复杂度

javascript - ajax错误时中断循环

loops - Clojure - 循环变量 - 不变性

c++ - 一个大池还是几个特定类型的池?

c - 使用网络内核扩展监控网络数据包

c++ - 在 cstring 中搜索运算符

c++ - BOOST_FILESYSTEM_VERSION 2 path.native_file_string() 的 BOOST_FILESYSTEM_VERSION 3 模拟是什么?

c# - 参数中的数据值正在被复制到其他参数 c++、c#

c# - 如何释放虚拟内存?

c++ - 返回值优化和构建结构的函数