简化简单的 C++代码——类似于 Python 的任何代码
现在,我有这样的代码:
bool isAnyTrue() {
for(std::list< boost::shared_ptr<Foo> >::iterator i = mylist.begin(); i != mylist.end(); ++i) {
if( (*i)->isTrue() )
return true;
}
return false;
}
我时不时地使用过Boost,但我真的不记得有什么简单的方法来编写它,有点像我用Python编写它,例如:
def isAnyTrue():
return any(o.isTrue() for o in mylist)
STL/Boost中有没有任何构造可以编写或多或少像这样?
或者也许是与此 Python 代码等效的代码:
def isAnyTrue():
return any(map(mylist, lambda o: o.isTrue()))
主要是我想知道 Boost / STL 中是否存在任何现有的任何
(和所有
)等效项。或者为什么没有(因为它看起来非常有用,而且我在 Python 中经常使用它)。
Right now, I have this code:
bool isAnyTrue() {
for(std::list< boost::shared_ptr<Foo> >::iterator i = mylist.begin(); i != mylist.end(); ++i) {
if( (*i)->isTrue() )
return true;
}
return false;
}
I have used Boost here and then but I couldn't really remember any simple way to write it somewhat like I would maybe write it in Python, e.g.:
def isAnyTrue():
return any(o.isTrue() for o in mylist)
Is there any construct in STL/Boost to write it more or less like this?
Or maybe an equivalent to this Python Code:
def isAnyTrue():
return any(map(mylist, lambda o: o.isTrue()))
Mostly I am wondering if there is any existing any
(and all
) equivalent in Boost / STL yet. Or why there is not (because it seems quite useful and I use it quite often in Python).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C++ 还没有
foreach
结构。你必须自己写/也就是说,你可以在这里使用
std::find_if
算法:另外,你可能应该使用
std::vector
或std::deque
而不是std::list
。编辑:sth刚刚告诉我,这实际上不会编译,因为你的列表包含
shared_ptr
而不是实际的对象......因此,你将需要编写自己的仿函数,或者依赖 boost:注意,我还没有测试过第二个解决方案。
C++ does not (yet) have a
foreach
construct. You have to write that yourself/That said, you can use the
std::find_if
algorithm here:Also, you should probably be using
std::vector
orstd::deque
rather thanstd::list
.EDIT: sth has just informed me that this won't actually compile because your list contains
shared_ptr
instead of the actual objects... because of that, you're going to need to write your own functor, or rely on boost:Note, I haven't tested this second solution.
我会使用自定义的any 而不是find_if。与 find_if 相比,我更喜欢它的可读性,但这是一个品味问题。
编辑:用 Billy ONeal 的 find_if 替代 any 。
Instead of find_if I'd go with a custom any. I like it better in terms of readability over find_if but that's a matter of taste.
Edit: Alternative any with find_if by Billy ONeal.
新的C++标准有std::any_of,例如
VS2010已经实现了这个。
The new C++ standard has std::any_of, e.g.
VS2010 has this implemented.