Supporting operations at multiple aggregation levels
Suppose I have struct or class that looks something like this:
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?
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
is e.g. a std::vector<foo>
.
精彩评论