fork download
  1. #include <iostream>
  2. #include <set>
  3. #include <vector>
  4.  
  5. std::vector<std::pair<int, int>> find_sums(const std::set<int>&s, int total)
  6. {
  7. if (s.empty()) {
  8. return {};
  9. }
  10. auto b = s.begin();
  11. auto e = s.end();
  12. --e;
  13.  
  14. std::vector<std::pair<int, int>> res;
  15. do {
  16. auto sum = *b + *e;
  17. if (sum == total) {
  18. res.push_back({*b, *e});
  19. ++b;
  20. } else if (sum < total) {
  21. ++b;
  22. } else { // sum > total
  23. if (e == s.begin()) {
  24. break;
  25. }
  26. --e;
  27. }
  28.  
  29. } while (b != e);
  30.  
  31. return res;
  32. }
  33.  
  34. void print(const std::vector<std::pair<int, int>>& pairs)
  35. {
  36. for (const auto& p : pairs) {
  37. std::cout << "{" << p.first << ", " << p.second << "} ";
  38. }
  39. std::cout << std::endl;
  40. }
  41.  
  42.  
  43. int main() {
  44. print(find_sums({1, 3, 5, 7, 11, 20}, 10)); // {3, 7}
  45. print(find_sums({1, 3, 5, 7, 11, 20}, 12)); // {1, 11}, {5, 7}
  46. }
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
{3, 7} 
{1, 11} {5, 7}