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