Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Just make sure you're accumulating integers and not doubles!


  #include<cstdio>
  #include<numeric>
  #include<vector>
  
  using namespace std;
  
  template <class T, template<class> class Cont>
  T sum(Cont<T> x)
  {
    return accumulate(x.begin(), x.end(), (T)0);
  }
    
  int main(int argc, char *argv[])
  {
    vector<double> ds({1.1, 2.2, 3.3, 4.4}); 
    vector<float> fs({1.1f, 2.2f, 3.3f, 4.4f});
    vector<int> is({1, 2, 3, 4});
    vector<unsigned long long> ulls({1ul, 2ul, 3ul, 4ul});

    printf("doubles: %f\n",sum(ds));
    printf("floats: %f\n",sum(fs));
    printf("ints: %d\n",sum(is));
    printf("ulls: %llu\n",sum(ulls));

    return 0;
  }


Obviously, you have to use

   std::accumulate(v.cbegin(), v.cend(), decltype(*v.cbegin()){});
:) :) :)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: