NathanOliver
Veteran Poster
1,084 posts since Apr 2009
Reputation Points: 215
Solved Threads: 189
Now, your question could be interpreted in a few ways. The ambiguity probably comes from a language difference.
A random vector for those four colours is best achieved via a shuffle algorithm.
I assume you want to return a vector with all four colours except in a different order.
If you're unfamiliar with the std::shuffle function ... don't quote me on that just - it's been a while... You could achieve something similar by randomly picking twoelements and swapping their contents perhaps?
iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
If your problem corresponds to iamthwee's interpretation, then his solution is appropriate.
If your problem is that you want to create a vector of arbitrary size where each element is one of the four color-strings, picked at random. Then, a simple solution is to map each color to a number and generate the numbers randomly (e.g. with rand() for a quick and easy solution). As so:
#include <map>
#include <string>
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
map< int, string> words;
words[0] = "red";
words[1] = "blue";
words[2] = "green";
words[3] = "yellow";
srand((unsigned int)time(NULL));
vector<string> v(10); // create a vector of 10 elements.
for(vector<string>::iterator it = v.begin(); it != v.end(); ++it) {
*it = words[rand() % 4];
cout << *it << endl;
};
return 0;
};
mike_2000_17
Posting Virtuoso
2,139 posts since Jul 2010
Reputation Points: 1,634
Solved Threads: 457
You want to use random_shuffle function,
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
int main(){
using namespace std;
const int COLOR_SIZE = 4;
string colors[COLOR_SIZE ] = { "yellow", "green", "blue" , "red" }
std::vector<string> colorVec( colors, colors + COLOR_SIZE );
//shuffle colors
std::random_shuffle( colorVec.begin(), colorVec.end() );
//do stuff with colorVec like print it
for(int i = 0; i < colorVec.size(); ++i){
cout << colorVec[i] << endl;
}
}
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608