fork download
  1. #include <initializer_list>
  2. #include <iostream>
  3. #include <iterator>
  4. #include <numeric>
  5. #include <string>
  6.  
  7. template <typename T>
  8. T add_select(const T* arr, std::initializer_list<std::size_t> selection)
  9. {
  10. using std::begin; using std::end;
  11. return std::accumulate(begin(selection), end(selection), T(), [=](T a, std::size_t b) { return a + arr[b]; });
  12. }
  13.  
  14. int main()
  15. {
  16. int p[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  17. int sum = add_select(p, { 5, 4, 7 });
  18. std::cout << sum << '\n';
  19.  
  20. std::string s[9] = { "abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vwx", "yz" };
  21. std::string result = add_select(s, { 2, 4, 6 });
  22. std::cout << result << '\n';
  23. }
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
16
ghimnostu