3

I hear that spirit is really fast at converting string to int.

I am however unable to create a simple function that can do so. Something like

int string_to_int(string& s) { /*?????*/ }

Can anybody use boost spirit to fill in this function.

By the way I am working on boost 1.34 and not the latest version.

rahul
  • 2,269
  • 3
  • 28
  • 31
  • 1
    Its not "really" fast, it just runs at a normal rate. Ever heard of the saying, in the land of the blind, the one eyed man is king? –  Jan 02 '11 at 02:59

2 Answers2

11

There are several ways to achieve this:

#include <boost/spirit/include/qi_parse.hpp>
#include <boost/spirit/include/qi_numeric.hpp>

namespace qi = boost::spirit::qi;

std::string s("123");
int result = 0;
qi::parse(s.begin(), s.end(), qi::int_, result);

or a shorter:

#include <boost/spirit/include/qi_parse.hpp>
#include <boost/spirit/include/qi_numeric.hpp>
#include <boost/spirit/include/qi_auto.hpp>    
namespace qi = boost::spirit::qi;

std::string s("123");
int result = 0;
qi::parse(s.begin(), s.end(), result);

which is based on Spirit's auto features. If you wrap one of these into a function, you get what you want.

EDIT: I saw only now that you're using Boost 1.34. So here is the corresponding incantation for this:

#include <boost/spirit.hpp>

using namespace boost::spirit;

std::string s("123");
int result = 0;
std::string::iterator b = s.begin();
parse(b, s.end(), int_p[assign_a(result)]);
maxschlepzig
  • 35,645
  • 14
  • 145
  • 182
hkaiser
  • 11,403
  • 1
  • 30
  • 35
  • Thanks. I see in my profiler that its about 2.5X faster than atoi. – rahul Oct 17 '10 at 08:10
  • At least with Boost 1.58 you have to change includes to make it compile. `parse` to `qi_parse`. And also you have to add `qi_auto` for the shorter version to compile. – Adam Badura Jun 06 '15 at 23:48
3

int i = boost::lexical_cast<int>(str);

Alexey Malistov
  • 26,407
  • 13
  • 68
  • 88
  • 6
    I've read on a couple occasions that boost::lexical cast is really slow for such trivial conversions. See also http://stackoverflow.com/questions/1250795/very-poor-boostlexical-cast-performance – Ralf Oct 15 '10 at 08:56