How to randomly choose an index from an array?

Hello,

How can I print randomly an index from an array, like can i have a sample code?

ex.

string items[] = {"item1", "item2", "item3", "item4", "item5"};

cout << "randomly prints an item from the array items" << endl;
If you want to print out all of them, use the .size() function.
1
2
3
4
for( int counter = 0; counter < items.size(); ++counter )
{
    cout << items[counter];
}

Or if you want to just output one item, you'd go
1
2
3
cout << items[itemLocation]; 
// itemLocation being a whole NON-NEGATIVE number (int, size_t, etc) 
// specifying the location of the data item in your array 

Now, to directly address your question, just make itemLocation a rand() function which selects between 0 and your array's (size - 1).
Last edited on
Topic archived. No new replies allowed.