You should be able to write this a lot simpler. Also, the reason your code seems to be not getting any random values is because your pushing back your bound with myVec.push_back(number)
. You should instead be doing myVec.push_back(result)
.
As for your actual question, it doesn't seem like your code is written as to what you're trying to achieve. If you want to get values 0-4 greater than the subsequent value, it would be better to write it something like this:
#include <iostream>
#include <ctime>
#include <random>
#include <vector>
int main(){
srand(time(0));
std::vector<int> nums;
int lower = 0;
for(int i=0; i<100; i++) {
// generate random number from lower bound to upper bound
// starting lower bound is 0
nums.push_back((rand() % 5) + lower);
lower = nums[nums.size()-1];
}
for(int num : nums){
std::cout << num << " ";
}
std::cout << "\n";
return 0;
}
So, generally, if a random function is returning any value x where 0 <= x < 1
(which I believe C/C++ rand() does), then to get a value within a given range you want to have it in this format:
(rand() % (upper_bound - lower_bound + 1)) + lower_bound
However, you said that you want all values to be 0-4 greater than the lower bound. This means we essentially want to start from our lower bound, and add 0-4 to it. So really, we just need to generate a random number from 0-4. The code above does rand() % 5
because rand() % N
will return any number x where 0 <= x < N
. So, we want to do rand() % 5
which will get any number from 0 to 4.
Also, this is just semantics, but in my personal experience it's always good to try and maintain some level of inference with your variable naming. In your for-each loop you wrote for(int vec : myVec)
, but to the glancing eye this may appear that myVec is actually a vector of vectors, and every element of myVec is a vector itself. Although the type int
is clearly declared, it's still easy to get confused as to why the developer named it "vec" if its type is not a vector. Once again, some of this comes down to preference and if this is for a personal project, assignment, or actual production code. But I'd start making a good habit of making sure things are named intentionally and purposefully.