Pergunta

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;
}
Foi útil?

Solução 2

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();

Outras dicas

This call is not right:

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

You should use x.size() instead to get the size of the vector.

what you do in the above line is - compute the size of x.capacity() - 1 which is an integer and then divide it by the size of an integer. Thus length is always 1 and so rand()%length is always 0.

I think you just want to use x.size(), instead of length:

randomNumber = x[rand() % x.size()];
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top