c++ - 是否可以打印宽度为5的 vector 内容?

标签 c++ arrays vector

这就是我必须做的!

编写一个程序来执行以下步骤。

动态分配内存来存储 10 个整数的数组。 为每个 int 分配一个 1 到 100 之间的随机值。 将 10 个随机整数分别复制到整数 vector 中。 打印动态分配的整数数组和整数 vector ,每个数组的宽度均为 5,如下面的示例输出所示。

我对最后一点有疑问。我的代码工作正常,但我不知道如何设置整数 vector 的宽度,因此它与整数数组相同。

#include<iostream>
#include<iomanip>
#include<cstdlib>
#include <vector>
#include <algorithm>
#include <iterator>
#include <stdexcept>

using namespace std;

int main(){

    const int SIZE = 10;
    int *arr = new int[SIZE];

    //assign rand numbers between 0 and 100
    for (int i = 0; i < SIZE; ++i){
        *(arr + i) = rand() % 100+1;
    }

    //print array
    for (int i = 0; i < SIZE; ++i){
        cout << setw(5) << *(arr +i) << " ";
    }
    std::vector<int> integers (arr, arr + 10);
    std::ostream_iterator<int> output(cout, " ");

    cout << endl;
    cout << "Vector integers contain: " << endl;
    std::copy(integers.begin(), integers.end(), output);

    return 0;
}

最佳答案

您的代码可以正常工作。 cout << setw(5);设置宽度就好了。您还可以使用cout.width(5); .

关于c++ - 是否可以打印宽度为5的 vector 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19394794/

相关文章:

c++ - 迭代对 vector

c++ - 从不同的架构加载 dylib

c# - 托管和非托管代码的内存分配分析器?

python - 仅从数组中的大元素中减去 10000

javascript - 阵列上的forEach在ie11中不起作用

c++ - 段错误(核心转储)- 具有多维 vector 的循环 C++98

vector - 用两点旋转线

c++ - 系统/统计 S_ISDIR(m) 与结构 dirent

c++ - 使用 std::vector.push_back() 时出现错误 C2280

C:如何纠正这个段错误