【问题标题】:Negate boost is_directory in std algorithm在 std 算法中否定 boost is_directory
【发布时间】:2011-11-20 05:39:18
【问题描述】:
boost::filesystem::recursive_directory_iterator end, begin(directory);

auto num_of_files=std::count_if(begin, end, 
        std::not1(boost::filesystem::is_directory)));

我试图否定上述目录迭代器上的函数 is_directory ,但我遇到了障碍。我尝试将not1 的模板指定为bool(*)(const boost::filesystem::path&),并尝试静态转换函数均未成功。

我知道我可以求助于 lamdba,但如果它有效,这会更干净。

谢谢

【问题讨论】:

    标签: c++ boost c++11 negate


    【解决方案1】:

    std::not1 需要一个函数对象作为其参数。这个函数对象可以通过std::ptr_fun获得,所以应该可以:

    auto num_of_files=std::count_if(begin, end, 
            std::not1(std::ptr_fun((bool(*)(const boost::filesystem::path&))boost::filesystem::is_directory)));
    

    (括号的数量可能不正确)。顺便说一句,您需要强制转换,因为 is_directory 是一个重载函数。

    但是,由于您标记了问题 c++11,因此您可以使用 lambda:

    auto num_of_files=std::count_if(begin, end, [](const boost::filesystem::path& p) { return !boost::filesystem::is_directory(p); });
    

    【讨论】:

    • 啊,我迟到了 30 秒 :)
    • 发挥了作用 我更喜欢这种语法,它对我来说更好读: ...std::ptr_fun(boost::filesystem::is_directory) ...
    • @111111,你疯了,或者可能是个机器人。我的意思是尽可能客气地说。
    【解决方案2】:

    not1 接受一个仿函数类的实例,它应该是一个Adaptable Predicate(即返回值的类型定义等),而您正试图用一个函数指针来提供它。所以你需要将它包装在一个仿函数中,ptr_fun 可能会有所帮助。 也许这会起作用(假设 using namespace std; using namespace boost;):

    auto num_of_files=count_if(begin, end, not1(ptr_fun(filesystem::is_directory)));
    

    【讨论】:

      【解决方案3】:

      你需要ptr_fun,

      这个相当精细的插图应该打印三遍1:(另见http://ideone.com/C5HTR

      #include <functional>
      #include <string>
      #include <algorithm>
      #include <iostream>
      
      bool pred(const std::string& s)
      {
          return s.size() % 2;
      }
      
      int main()
      {
          std::string data[] = { "hello", "world!" };
      
          std::cout << std::count_if(data, data+2, 
                  pred) << std::endl;
      
          std::cout << std::count_if(data, data+2, 
                  std::ptr_fun(pred) ) << std::endl;
      
          std::cout << std::count_if(data, data+2, 
                  std::not1(std::ptr_fun(pred))) << std::endl;
      
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-18
        • 2011-01-13
        • 2013-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多