2010-11-09 36 views
0

假設我的結構或類看起來像這樣: 在多個聚合級別的支持操作

 
struct foo{ 
    string attribute_1; 
    int attribute_2; 
    string attribute_3;

int value_1; int value_2; double value_3; };

What are some good ways of supporting aggregate operations on collections of foo across the different attributes? E.g. I might want to sum value_1 where attribute_1 is something, or where attribute 2 is something and attribute 3 is something.

I have been using boost::multi_index to do this but I'd like to hear how other people do this. Perhaps when you need this kind of ability, it's better to use to embed an in-memory database. What have other people done for this?

回答

0

STL algorithms and functors will allow you to do this sort of thing in many ways. For instance, to sum value_1 where attribute_1 is something, you could do something like (DISCLAIMER: This hasn't been near a compiler)

class MyFunctor 
{ 
public: 
    explicit MyFunctor(const string &str) : str_(str), sum_(0) {} 
    bool operator() (const foo &f) const 
    { 
     if (f.attribute_1 == str_) 
     { 
      sum_ += f.value_1; 
     } 
    } 
    int sum() const { return sum_; } 

private: 
    string str_; 
    int sum_; 
}; 

... 


std::cout << stl::for_each(v.begin(), v.end(), MyFunctor("blah")).count() << std::endl; 

where v是例如一個std::vector<foo>