遇到 'for_each' is not a member of 'std' 的问题

       今天学Boost库时候用到 标准库的 for_each , 但是编译总是出错,提示:

        error: 'for_each' is not a member of 'std' 或者  for_each was not declared in this scope

   这是因为缺少头文件 #include ,还有不要忘记using namespace std; 或者用std::for_each。

   在http://ubuntuforums.org/showthread.php?t=965086的4楼找到的答案。


顺便提一下for_each用法和boost::bind调用成员函数的优点:

#include 
#include 
#include 
#include 
class status
{
    std::string name_;
    bool ok_;
public:
    status(const std::string& name):name_(name),ok_(true) {}
    void break_it()
    {
        ok_=false;
    }
    bool is_broken() const
    {
        return ok_;
    }
    void report() const
    {
        std::cout << name_ << " is " <<
                  (ok_ ? "working nominally":"terribly broken") << '\n';
    }
};
int main(int argc, char** argv)
{
    std::vector statuses;
    statuses.push_back(status("status 1"));
    statuses.push_back(status("status 2"));
    statuses.push_back(status("status 3"));
    statuses.push_back(status("status 4"));
    statuses[1].break_it();
    statuses[2].break_it();
    std::for_each(
        statuses.begin(),
        statuses.end(),
    /// std::mem_fun_ref(&status::report)
        boost::bind(&status::report, _1)
                  );
    return 0;
}    

    这样就逐一调用了vector型statuses中每个status类的report成员函数,也许

这和用std::mem_fun_ref没有什么区别,但是当你改用指针时候就不同了,需要用

std::mem_fum而不是mem_fum_ref:

    std::vector statuses;
    statuses.push_back(new status("status 1"));
    statuses.push_back(new status("status 2"));
    statuses.push_back(new status("status 3"));
    statuses.push_back(new status("status 4"));
    statuses[1]->break_it();
    statuses[2]->break_it();
    std::for_each(  
      p_statuses.begin(), 
      p_statuses.end(), 
///   std::mem_fun(&status::report)
      boost::bind(&status::reprot, _1)
    );
    但是如果用boost::bind就不必担心这些了,语法是不变的。


注:代码源自《Beyond the C++ Standard Library: An Introduction to Boost》Library9.


你可能感兴趣的:(编程,boost,bind,c++,C++,STL,错误)