Summing struct members inside a vector

后端 未结 5 1067
闹比i
闹比i 2020-12-29 08:22

Consider the following:

typedef struct {
    int a;
    int b;
    int c;
    int d;
} ABCD;

typedef std::vector VecABCD;

Say

5条回答
  •  温柔的废话
    2020-12-29 08:58

    You could use for_each. Its an option.

    #include 
    #include 
    #include 
    
    using namespace std;
    typedef struct{
        int a;
    
    }ABCD;
    
    typedef vector vecABCD;
    
    struct sum  : public unary_function
    {
      sum(){count.a=count.b=count.c=count.d=0;}
      void operator() (ABCD x) {
           count.a+=x.a;
           count.b+=x.b;
           count.c+=x.c;
           count.d+=x.d;
       }
      ABCD count;
    };
    
    int main()
    {
    
      ABCD s1={1,2,3,4};
      ABCD s2={5,6,7,8};
    
      vecABCD v;
      v.push_back(s1);
      v.push_back(s2);
      sum s = for_each(v.begin(), v.end(), sum());
      cout<

    output:

    4
    

提交回复
热议问题