BOOST_FOREACH 使用及注意事项

BOOST_FOREACH可以简化便利操作。

例如

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

int main()
{
    std::vector<int> vInt;
    for(int i = 0; i < 10; i++) {
        vInt.push_back(i);
    }

    BOOST_FOREACH(int n, vInt) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    return 0;
}

但是如果在使用BOOST_FOREACH的过程中,删除容器中的元素,程序会出现异常,迭代器会失效。

合理的操作是在遍历完,搜集要删除的元素放在一个临时容器中再进行删除操作。

猜你喜欢

转载自blog.csdn.net/guoguangwu/article/details/89333793
今日推荐