c++ - 在 C++ 中使用 vector 创建随机数

标签 c++ vector

我正在构建一个程序,用户在其中键入一个数字 (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/

相关文章:

c++ - 将指向对象的指针保存在循环中的 Vector 中

c++ - 将 cv::Mat 转换为 vector<int>

c++ - 仅打印 QPlainTextEdit 文档纯文本

c++ - 如果条件在 C++ 中执行顺序

c++ - 对齐数据类型 Eigen::Matrix 的数组或 vector 声明

.net - 如何在不需要运行 .net 框架的情况下创建 C++ 程序(如 ccleaner 和 utorrent)

c++ - 在构造函数中初始化 vector C++

c++ - 如何将整个流读入 std::vector?

c++ - vector 中的结构成员是否在 C++ 中初始化为零?

c++ - 它如何在内存中使用指针和一般情况下工作?