atoi on a character array with lots of integers

前端 未结 2 401
感情败类
感情败类 2021-01-16 15:02

I have a code in which the character array is populated by integers (converted to char arrays), and read by another function which reconverts it back to integers. I have use

2条回答
  •  醉梦人生
    2021-01-16 15:27

    There is absolutely no reason for the Karma/Qi text version to be any slower than the STL version. I improved @sehe implementation of the Karma/Qi text version to reflect that claim.

    The following Boost Karma/Qi text version is more than twice as fast as the STL version:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    namespace ascii = boost::spirit::ascii;
    namespace qi = boost::spirit::qi;
    namespace karma = boost::spirit::karma;
    namespace phoenix = boost::phoenix;
    
    
    template 
    void generate_numbers(OutputIterator& sink, const std::vector& v){
    
      using karma::int_;
      using karma::generate_delimited;
      using ascii::space;
    
      generate_delimited(sink, *int_, space, v);
    }
    
    template 
    void parse_numbers(Iterator first, Iterator last, std::vector& v){
    
      using qi::int_;
      using qi::phrase_parse;
      using ascii::space;
      using qi::_1;
      using phoenix::push_back;
      using phoenix::ref;
    
      phrase_parse(first, last, *int_[push_back(ref(v), _1)], space);
    }
    
    int main(int argc, char* argv[]){
    
      static boost::mt19937 rng(0); // make test deterministic
      std::vector data;
      data.resize(2 << 24);
      std::generate(data.begin(), data.end(), rng);
    
      std::string astext;
      std::back_insert_iterator out(astext);
      generate_numbers(out, data);
    
      //std::cout << astext << std::endl;
    
      std::string::const_iterator begin(astext.begin()), end(astext.end());
      std::vector clone;
      parse_numbers(begin, end, clone);
    
      //verify that clone now contains the original random data:
      //std::copy(clone.begin(), clone.end(), std::ostream_iterator(std::cout, ","));
    
      return 0;
    }
    

提交回复
热议问题