fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. struct Obj {
  5. int a;
  6. int b;
  7. };
  8.  
  9. std::unique_ptr<int[]>
  10. fn(Obj* os, size_t N, std::function<int(const Obj&)> keyFn)
  11. {
  12. auto arr = std::make_unique<int[]>(N);
  13. for (size_t i = 0; i < N; ++i) {
  14. arr[i] = keyFn(os[i]);
  15. }
  16. return arr;
  17. }
  18.  
  19. int main() {
  20. Obj os[] { { 1, 10 }, { 2, 20 } };
  21.  
  22. auto a1 = fn(os, 2, [](const Obj& o){ return o.a; });
  23. auto a2 = fn(os, 2, [](const Obj& o){ return o.b; });
  24.  
  25. for (size_t i = 0; i < 2; ++i) {
  26. std::cout << i << ": " << a1[i] << ", " << a2[i] << '\n';
  27. }
  28. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
0: 1, 10
1: 2, 20