English 中文(简体)
如何在通用的++代码中明确“双重”?
原标题: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.

最佳回答

To initialize it:

T ave = T();

并重新制定:

ave = T();
问题回答

<ave is a commd_ptr<T>tries this to resetave to aail- originalized T:

*ave = T();




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签