问题
I try to use for_each from the C++ boost library. This is the code that I have.
#include <iostream>
#include <vector>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <boost/fusion/include/for_each.hpp>
using namespace std;
int main() {
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
boost::for_each(
vec,
[](int val){
cout << val << "\n";
}
);
return 0;
}
This is how I compile my code:
g++ -std=c++0x -I /opt/software/boost/1.50_ubuntu12.4lts_gcc4.7.2/include -c try_boost.cpp
g++ -o try_boost -L/opt/software/boost/1.50_ubuntu12.4lts_gcc4.7.2/lib try_boost.o -lboost
As a result I get:
error: ‘for_each’ is not a member of ‘boost’
Does anybody know why it does not work?
回答1:
You're using for_each from Boost.Fusion Library. That doesn't work with std::vector.
The for_each which you need is from Boost.Range Library.
#include <boost/range/algorithm/for_each.hpp> //note this difference!
boost::for_each(vec, your-lambda-expression);
It is defined inside boost::range namespace, which is brought to boost namespace using using declarative. So you can also write this:
boost::range::for_each(vec, your-lambda-expression);
来源:https://stackoverflow.com/questions/15527999/how-to-use-for-each-from-c-boost-library