random generator binary numbers

according to this random generator number code:

srand(time(0));
for (i = 1; i <= 26; i++)
{
bufferData.push_back(i);
}
for (i = 1; i <= bufferData.size(); i++)
{
bufferData[i] = rand() % 2;
std::cout << bufferData[i] % 2 << " ";
}

is it possible to write it in one loop and statement?
First, your code is wrong because array/vector indices start at [0], not [1]. You're invoking undefined behavior in the last iteration of your second for loop.
Change to for (i = 0; i < bufferData.size(); i++).

is it possible to write it in one loop and statement?


1
2
3
4
5
6
7
8
srand(time(0));
std::vector<int> bufferData(26); // initialize with 26 size

for (int i = 0; i < bufferData.size(); i++)
{
    bufferData[i] = rand() % 2;
    std::cout << bufferData[i] % 2 << " ";
}

Shortening it further (ex: combining the assignment with the cout) would just lead to unreadable code, imo.
Last edited on
vector <bool> is sometimes optimized to store single bits on many implementations. A full vector of int (32 or 64!) is 32 to 64 times bigger than it needs to be.

if you just want 26 bits, you can fit that into a 32 bit int:
int i = rand(); //done. random stream of up to 32 bits!

and you can fish out each bit with logic operations, eg
i & 1; (the first bit)
i & 2; (the second bit)
i & 4; (third bit) .... 8, 16, 32, ... etc bits

you can use the above to load up the vector bool if you need vectorish things done, or you can just keep it stored in the integer as if that were an array of bits, and access it as needed directly, depending on what you need done. If 26 is just an example and you needed something bigger than 64, this won't help you.
Last edited on
Topic archived. No new replies allowed.