fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <algorithm>
  5.  
  6. std::vector<std::pair<int,std::string>> cities;
  7.  
  8. void add_city(const std::string &name, int pop) {
  9. if (cities.empty()) {
  10. cities.emplace_back(pop, name);
  11. }
  12. else {
  13. cities.emplace_back(pop + cities.back().first , name);
  14. }
  15. }
  16.  
  17. int total_population() {
  18. return cities.empty() ? 0 : cities.back().first;
  19. }
  20.  
  21. const std::string select_city() {
  22. const int total = total_population();
  23. const int pos = std::rand() % total;
  24. const auto iter = std::lower_bound(begin(cities), end(cities), std::make_pair(pos, std::string()));
  25. return iter->second;
  26. }
  27.  
  28. int main() {
  29.  
  30. add_city("A", 50);
  31. add_city("B", 500);
  32. add_city("C", 1000);
  33.  
  34. for (unsigned i=0; i<15; ++i) {
  35. const std::string city = select_city();
  36. std::cout << city << ' ';
  37. }
  38.  
  39. return 0;
  40. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
C A B C B B B C C C C C B B C