waqqasfarooq.com

  • Increase font size
  • Default font size
  • Decrease font size
Home Useful Code Snippets Getting random element from STD collection


Getting random element from std collection

E-mail Print PDF
User Rating: / 13
PoorBest 

The following code snippet gives a quick way of selecting an element at random from a std collection.


typedef std::vector  Countries;
 
Countries countries;
countries.push_back("Pakistan");
countries.push_back("Canada");
countries.push_back("United States");
countries.push_back("Japan");
countries.push_back("France");
countries.push_back("Germany");
 
Countries::iterator randIt = countries.begin();
std::advance(randIt, std::rand() % countries.size());
 
std::cout << "Random selection: " << *randIt << std::endl;


 

Comments  

 
0 #2 Waqqas Farooq 2010-09-16 16:18
Quoting roommate:
I don't want to get any random element from an STD collection. Chose your words carefully my friend :-) :P


Hahahaha, didn't think of it in those terms. :lol:

On a serious note: std is a shortform for 'standard' and this is a package (namespace) that provides a lot of data structures.
 
 
+2 #1 roommate 2010-09-16 15:48
I don't want to get any random element from an STD collection. Chose your words carefully my friend :-) :P