通过指针向量累加
所以我需要使用累加对向量中的一些双精度进行求和,其中我的 VECTOR 实际上是指向对象的指针.
So I need to sum some doubles that are in a vector using accumulate, where my VECTOR is actually a pointer to objects.
现在,当我对 initVal 使用带有 int 的累加时,它运行给我一个类似 -3.3695e+008 的答案,但是当我在那里放一个 double 时,我得到'+':指针加法需要整数操作数".我尝试了很多方法来解决它,考虑到在累加算法中传递的指针,我搜索了一些关于解引用迭代器的东西,但我无法解决我的问题(我猜是由于未到期)积累:
Now when I use accumulate with an int for the initVal it runs giving me an answer like -3.3695e+008 but when I put a double there I get that "'+' : pointer addition requires integral operand". I tryed lots of ways to fix it, thinking its about the pointers getting passed in the accumulate algorythm and I searched some stuff about Dereferencing iterator but I couldnt come to a solution to my problem (due to unexpireance I guess) Accumulate:
void calcDMean(){
dMean= 0.0 ;
vector<CData*> :: iterator it = m_vectorData.begin();
int n = m_vectorData.size();
// dMean = accumulate(m_vectorData.begin(), m_vectorData.end(), 0.0);
dMean = accumulate(it,m_vectorData.end(),0.0);
dMean = dMean/n;
}
还有一些其余的代码(数据通过第二个类中的文件构造函数"传递:
And some of the rest of the code (the Data is passed trough a "file constructor" in the second class:
class CData {
int m_iTimeID;
double m_dData;
public:
CData (){
m_iTimeID = 0;
m_dData = 0;
}
CData (const CData& obekt){ //Copy
m_iTimeID=obekt.m_iTimeID;
m_dData=obekt.m_dData;
}
int getID() const{ //GET ID
return m_iTimeID;}
double getData() const { //GET DATA
return m_dData;}
double operator+(CData &obekt){
return (m_dData + obekt.m_dData);
} ;
double operator+(double b){
return (m_dData + b);
} ;
};
class CCalc3SigmaControl {
vector<CData*> m_vectorData;
double sigmaUp;
double sigmaDown;
double dMean;
你的问题是你的向量存储了指针,所以std::accumulate
将计算指针的总和.
The problem you have is that your vector stores pointers, so the std::accumulate
will calculate the sum of the pointers.
您必须使用 std::accumulate
的四参数版本,并提供您自己的函数来正确进行计算,例如
You have to use the four-argument version of std::accumulate
, and provide your own function which does the calculations properly, something like
dMean = std::accumulate(
m_vectorData.begin(), m_vectorData.end(), 0.0,
[] (const double acc, const CData* data) { return acc + data->getData(); }
);