// random_shuffle example
#include <iostream>
#include <algorithm>
#include <functional>
#include <vector>
#include <ctime>
#include <cstdlib>
usingnamespace std;
// random generator function:
ptrdiff_t myrandom (ptrdiff_t i) { return rand()%i;}
// pointer object to it:
ptrdiff_t (*p_myrandom)(ptrdiff_t) = myrandom;
int main () {
srand ( unsigned ( time (NULL) ) );
vector<int> myvector;
vector<int>::iterator it;
// set some values:
for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9
// using built-in random generator:
random_shuffle ( myvector.begin(), myvector.end() );
// using myrandom:
random_shuffle ( myvector.begin(), myvector.end(), p_myrandom);
// print out content:
cout << "myvector contains:";
for (it=myvector.begin(); it!=myvector.end(); ++it)
cout << " " << *it;
cout << endl;
return 0;
}
generates the code to show numbers 1-25 in no specific order.
However, I'm making a Battleships game and so I need a pointer that will point to the first value in the list for the computer's first go, then second on the second go etc. etc.
It says in the code that there is a pointer there but I can't for the life of me make it so that it only prints one value every time.
See lines 32-33. They walk the vector in order. For vector, you have two choices: either use an index and access it like an array, or use iterators as the code above does. Same code as 32 and 33, except using indices and array syntax:
1 2
for( size_t i = 0; i < myvector.size(); ++i )
cout << " " << myvector[ i ];