Search code examples
c++genericssmart-pointersgeneric-programming

how to clear `double` in generic c++ code?


I'm writing a function that averages every 10 units of a 100 unit vector. I have to clear a temporary sum after every 10 iterations. Normally, I would write ave=0.0 but if the ave is not a double but some type T, I run into problems. For example if I average over points with xyz coordinate,s I can't do {x,y,z} = 0.0

to work around, I tried to create a smart pointer and then reset it. that gave me seg fault. what is the best way to clear an object that doesn't have a specified type?

template <class T>
vector<T> average(const vector<T> &v, const int n) {
  vector<T> ave_vec;
  int iave = 0;
  shared_ptr<T> ave(new T);
  for (int i = 0; i < v.size(); i++) {
    *ave += v[i];
    iave++;
    if (iave == n) {
      ave_vec.push_back(*ave/n);
      ave.reset(); ///> gives seg fault
      iave=0;
    }
  }
  return ave_vec;
}

if I replace ave.reset() with ave = 0.0, the code works.


Solution

  • To initialize it:

    T ave = T();
    

    and to reset it:

    ave = T();