这就是我必须做的!
编写一个程序来执行以下步骤。
动态分配内存来存储 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/