【问题标题】:Boost filtered adaptor compilingBoost过滤适配器编译
【发布时间】:2014-05-24 03:58:01
【问题描述】:

我遇到了boost::adaptors::filtered 的问题。有演示问题的示例

struct IsRegex { 
  IsRegex() {} // filter_iterator requires default constructible predicate
  explicit IsRegex(const boost::regex &rx) : m_rx(rx) {}
  IsRegex(const IsRegex &isRegex) : m_rx(isRegex.m_rx) {}
  void swap(IsRegex &isRegex) { std::swap(m_rx, isRegex.m_rx); }
  IsRegex& operator=(IsRegex isRegex) { swap(isRegex); return *this; }

  bool operator() (const std::string &str) const {
    return boost::regex_match(str, m_rx);
  }
  boost::regex m_rx;
};

int main()
{
   std::string foo[] = {"0ii", "22", "48", "555", "15", "ab"};
   typedef std::list<std::string> Container;
   Container bar((foo), foo+5);
   const boost::regex rx(("\\d{2}"));
   IsRegex isRegex((rx));
   Container::iterator it 
         = boost::max_element(bar | boost::adaptors::filtered(isRegex));
}

不幸的是,我有

In function ‘int main()’:
error: conversion from 
‘boost::filter_iterator< IsRegex, std::_List_iterator<std::string> >’
to non-scalar type 
‘std::_List_iterator<std::string>’
requested

这种行为的原因是什么以及如何解决它?

【问题讨论】:

    标签: c++ boost compiler-errors c++03 boost-range


    【解决方案1】:

    你想用 .base() 映射来自适配迭代器的源迭代器:

    Container::iterator it = 
         boost::max_element(bar | boost::adaptors::filtered(isRegex))
         .base();
    

    另外,我可以建议修改谓词的命名来说明它的含义:

    #include <boost/range/adaptors.hpp>
    #include <boost/range/algorithm.hpp>
    #include <list>
    
    using namespace boost::adaptors;
    
    struct IsMatch { 
        IsMatch(const boost::regex &rx = boost::regex()) : m_rx(rx) {}
    
        bool operator() (const std::string &str) const {
            return boost::regex_match(str, m_rx); 
        }
      private:
        boost::regex m_rx;
    };
    
    int main()
    {
        std::string foo[] = {"0ii", "22", "48", "555", "15", "ab"};
    
        typedef std::list<std::string> Container;
        Container const bar(foo, foo+5);
    
        IsMatch isMatch(boost::regex("\\d{2}"));
    
        Container::const_iterator it = boost::max_element(bar | filtered(isMatch)).base();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-04
      • 1970-01-01
      • 2019-04-02
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      相关资源
      最近更新 更多