Pergunta

So I need to sum some doubles that are in a vector using accumulate, where my VECTOR is actually a pointer to objects.

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;  
Foi útil?

Solução

The problem you have is that your vector stores pointers, so the std::accumulate will calculate the sum of the pointers.

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(); }
);

Outras dicas

Use a lambda expression. Try the following

void calcDMean()
{
    double sum  = std::accumulate( m_vectorData.begin(), m_vectorData.end(), 0.0,
                                   []( double acc, CData *p ) 
                                   { return ( acc + p->getData() ); } );

    dMean = m_vectorData.size() == 0 ? 0.0 : sum / m_vectorData.size();
 }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top