C++ STL - 按顺序遍历所有内容 [英] C++ STL - iterate through everything in a sequence

查看:25
本文介绍了C++ STL - 按顺序遍历所有内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个序列,例如

std::vector< Foo > someVariable;

我想要一个循环来遍历其中的所有内容.

and I want a loop which iterates through everything in it.

我可以这样做:

for (int i=0;i<someVariable.size();i++) {
    blah(someVariable[i].x,someVariable[i].y);
    woop(someVariable[i].z);
}

或者我可以这样做:

for (std::vector< Foo >::iterator i=someVariable.begin(); i!=someVariable.end(); i++) {
    blah(i->x,i->y);
    woop(i->z);
}

这两个似乎都涉及相当多的重复/过度打字.用一种理想的语言,我希望能够做这样的事情:

Both these seem to involve quite a bit of repetition / excessive typing. In an ideal language I'd like to be able to do something like this:

for (i in someVariable) {
    blah(i->x,i->y);
    woop(i->z);
}

在一个序列中遍历所有内容似乎是一种非常常见的操作.有没有办法让代码的长度不是应有的两倍?

It seems like iterating through everything in a sequence would be an incredibly common operation. Is there a way to do it in which the code isn't twice as long as it should have to be?

推荐答案

您可以使用标准库中的 for_each.您可以将函子或函数传递给它.我喜欢的解决方案是BOOST_FOREACH,就像其他语言中的foreach.C+0x 会有一个顺便说一句.

You could use for_each from the standard library. You could pass a functor or a function to it. The solution I like is BOOST_FOREACH, which is just like foreach in other languages. C+0x is gonna have one btw.

例如:

#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/foreach.hpp>

#define foreach BOOST_FOREACH 

void print(int v)
{
    std::cout << v << std::endl;
}

int main()
{
    std::vector<int> array;

    for(int i = 0; i < 100; ++i)
    {
        array.push_back(i);
    }

    std::for_each(array.begin(), array.end(), print); // using STL

    foreach(int v, array) // using Boost
    {
        std::cout << v << std::endl;
    }
}

这篇关于C++ STL - 按顺序遍历所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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