我正在构建一个程序,用户在其中键入一个数字 (n) 并创建一组随机数。因此,例如,如果用户输入 8,则应创建八个随机数,它们的范围应为 0-999,999。该程序似乎正在编译,唯一的问题是,只生成了一个随机数。
#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;
main()
{
int n;
int r;
int i;
int j;
vector<int> v;
cout << "Enter size of vector: ";
cin >> n;
for (i = 0; i < n; i++)
{
v.push_back(n);
r = rand() % 1000000;
v[i] = r;
}
cout << r << endl;
谁能告诉我我做错了什么以及我需要做什么才能生成多个随机数?
最佳答案
明显的问题是什么:
for (int i=0; i<n; i++)
v.push_back(rand()%1000000);
看起来您正在生成正确数量的随机数,但当您完成后,您正在打印 r
而不是 v
,其中包含随机数。
编辑:std::vector
不支持 operator<<
直接,所以你可以使用循环打印出内容:
for (int i=0; i<v.size(); i++)
std::cout << v[i] << '\n';
或者您可以使用 std::copy
:
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n"));
当然还有其他各种可能性......
编辑 2:这是 Chris Lutz 在他的评论中建议的完整/正确版本:
#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
#include "infix_iterator.h"
template <typename T>
std::ostream& operator<<(std::ostream &o, const std::vector<T>& v) {
o << "[";
std::copy(v.begin(), v.end(), infix_ostream_iterator<T>(o, ", "));
o << "]";
return o;
}
#ifdef TEST
int main() {
std::vector<int> x;
for (int i=0; i<20; i+=2)
x.push_back(i);
std::cout << x << "\n";
return 0;
}
#endif
虽然这不是绝对必要的,但它使用了一个 ostream_infix_iterator
我前段时间发过。
关于c++ - 在 C++ 中使用 vector 创建随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4834444/