c++ - 从c++中的 vector 生成随机数

标签 c++ vector srand

我正在测试如何执行此操作,然后再尝试在我必须执行的更大程序中实现它并且出现问题。这段代码工作正常,但它继续只给出 vector 中的第一个数字。到底出了什么问题?

#include <iostream>
#include <string>
#include <vector>
#include "stdlib.h"
#include "time.h"

using namespace std;

int main()
{
    int randomNumber;
    int length;
    int i = 0;
    vector<int> x;
    x.push_back(12);
    x.push_back(1);
    x.push_back(6);
    x.push_back(34);
    x.push_back(23);

    srand(time(0));
    length = sizeof(x.capacity() - 1) / sizeof(int);

    while(i < 10){
        randomNumber = x[rand() % length];
        cout << randomNumber << endl;
        i++;
    }

    return 0;
}

最佳答案

这个调用是不对的:

length = sizeof(x.capacity() - 1)/sizeof(int);

您应该使用 x.size() 来获取 vector 的大小。

您在上一行中所做的是 - 计算 x.capacity() - 1 的大小,这是一个整数,然后将其除以整数的大小。因此,长度始终为 1,因此 rand()%length 始终为 0。

关于c++ - 从c++中的 vector 生成随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15734035/

相关文章:

c++ - 解决C++中的别名问题

c++ - 从控制台中删除单个字符

c++ - 如果对可推导类型进行替换,可变参数模板类型推导会使编译器崩溃

c++ - CMake:GLFW 作为外部项目

c++ - 合并排序 C++ 实现,无法识别代码中的错误

android - eclipse 中没有 std::find() 的匹配函数。在 XCode 中运行良好

c# - 如何仅从法向量获取下向量?

c++ - 初始化 srand 的推荐方法?

c++ - srand()的含义

c - rand() 没有给我随机数