Boost logo

Boost Users :

Subject: Re: [Boost-users] Static map like array or range?
From: Raymond Burkholder (ray_at_[hidden])
Date: 2013-09-15 16:43:41


> I find myself often building lookup tables for conversion or mapping of
one piece of data to another. Common conversions include 

> * converting from one string to a different string (e.g. text
translation), 
> * converting from an enum to a descriptive string
> * converting from a string to an enum
> * converting from a string to a function or functor

> The key aspect of these lookup tables is that they are static. If the
table is reasonably large, say 7-10 items, I ensure that the table is
presorted and use lower_bounds() to search the table. 

For the first, third, and fourth items, I sometimes use run-time created
Keyword Matching functions. I wrote about ways of doing this at:
http://blog.raymond.burkholder.net/index.php?/archives/129-A-Keyword-Matchin
g-Algorithm.html
http://blog.raymond.burkholder.net/index.php?/archives/371-Keyword-Matching-
non-text-streams.html

If built with static functions, then you get the 'build once, use many'
style of functionality. There are probably some additional optimizations.

The other way of doing this would be to use boost::spirit. You can use the
parser to parse a series of predefined string candidates and generate a
result. The parsers are built at compile time, and basically build a
compile structure of the run time structure I suggest above. If I recall
correctly, the compile time structure uses efficiently built tries for its
search.

For your second item, if your enums are close together, then I've heard that
compilers optimize switch statements quite handily, sometimes turning switch
statements into compile time indexed offset jump tables. You can't get much
faster than that. Otherwise using lower_bound on random_iterator capable
constructs seems to be the fastest way of doing things.

-- 
This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net