Search code examples
c++vectorsrand

Generating a random number from a vector in c++


I am testing how to do this before i try and implement it in a larger program that I have to do and an issue is arising. This code works fine but it continues to only give the first number in the vector. What exactly is going wrong?

#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;
}

Solution

  • The way you calculate the length of your vector is wrong:

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

    since capacity() returns the size of the storage space currently allocated for the vector, expressed in terms of elements and thus your length is equal to 1 in your example.

    You should use size() instead:

    length = x.size();