fork(2) download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <random>
  5.  
  6. /**
  7.  * Moves all elements in the input container
  8.  * that satisfy the given predicate
  9.  * into the output container,
  10.  * and erases them from the input container.
  11.  * @tparam Container The container type.
  12.  * @tparam UnaryPredicate The predicate type.
  13.  * @param in The input container.
  14.  * @param out The output container.
  15.  * @param predicate The predicate to satisfy.
  16.  */
  17. template <class Container, class UnaryPredicate>
  18. void move_and_erase_if(Container &in, Container &out, UnaryPredicate predicate) {
  19. // sort the input container so that all elements that
  20. // satisfy the predicate are moved to the end.
  21. auto it = std::partition(in.begin(), in.end(), predicate);
  22.  
  23. // move the elements satisfying the predicate
  24. // into the output container.
  25. std::move(in.begin(), it, std::back_inserter(out));
  26.  
  27. // erase the elements satisfying the predicate
  28. // from the input container.
  29. in.erase(in.begin(), it);
  30. }
  31.  
  32. int main() {
  33. std::default_random_engine generator;
  34. std::uniform_int_distribution<int> distribution(1,6);
  35.  
  36. std::vector<int> diceRolls(100);
  37. for (size_t i = 0; i < diceRolls.size(); i++) {
  38. diceRolls[i] = distribution(generator);
  39. }
  40.  
  41. std::vector<int> luckySixes;
  42. move_and_erase_if(diceRolls, luckySixes, [](int val){
  43. return val == 6;
  44. });
  45.  
  46. std::cout << "DICE ROLLS: ";
  47. for (auto val : diceRolls) {
  48. std::cout << val << " ";
  49. }
  50.  
  51. std::cout << "\nLUCKY SIXES: ";
  52. for (auto val : luckySixes) {
  53. std::cout << val << " ";
  54. }
  55.  
  56. return 0;
  57. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
DICE ROLLS: 1 3 5 4 3 1 4 1 4 3 5 5 5 2 1 5 2 4 5 4 3 2 1 5 5 4 1 4 1 2 3 5 3 2 2 3 1 3 5 4 1 3 4 4 2 5 3 2 1 5 1 4 3 2 1 4 3 2 1 5 5 5 1 1 5 4 4 5 5 3 5 2 2 3 4 4 1 3 1 2 3 
LUCKY SIXES: 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6