对容器中所有元素的成员函数结果求和的最佳方法是什么? [英] What's the best way to sum the result of a member function for all elements in a container?

查看:26
本文介绍了对容器中所有元素的成员函数结果求和的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下对象:

struct Foo
{
    int size() { return 2; }
};

获取 vector<Foo> 中所有对象的总 size 的最佳方法是什么(最易于维护、可读等)?我会发布我的解决方案,但我对更好的想法感兴趣.

What's the best way (most maintainable, readable, etc.) to get the total size of all objects in a vector<Foo>? I'll post my solution but I'm interested in better ideas.

更新:

到目前为止,我们有:

  • std::accumulate 和仿函数
  • std::accumulate 和 lambda 表达式
  • 普通的 for 循环

还有其他可行的解决方案吗?你可以使用 boost::bindstd::bind1st/2nd 使某些东西可维护吗?

Are there any other workable solutions? Can you make something maintainable using boost::bind or std::bind1st/2nd?

推荐答案

除了你自己的建议,如果你的编译器支持 C++0x lambda 表达式,你可以使用这个更短的版本:

In addition to your own suggestion, if your compiler supports C++0x lambda expressions, you can use this shorter version:

std::vector<Foo> vf;

// do something to populate vf


int totalSize = std::accumulate(vf.begin(),
                                vf.end(),
                                0, 
                                [](int sum, const Foo& elem){ return sum + elem.size();});

这篇关于对容器中所有元素的成员函数结果求和的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆