Boost logo

Boost :

Subject: Re: [boost] Re : BOOST_FOREACH like macro for map
From: Stewart, Robert (Robert.Stewart_at_[hidden])
Date: 2009-10-20 16:59:00


Pierre Morcello wrote:
> Hi mobi phil,
>
> > One of the annoyances with std::map is that if you work
> > with const maps, then
> > there is no "one line" code to get an element knowing the
> > key.
>
> If that is really what you want and you don't care about
> performances, I can propose you for example the following :
>
> struct ConstMapHelper
> {
> template <class T,class U>
> static const U& getConst(const T& pKey,const
> std::map<T,U>& pMap)
> {
> typedef std::pair<const T,U> TPair;
> BOOST_FOREACH(const TPair& lPair,pMap)
> {
> if(lPair.first==pKey)

That is horribly inefficient: O(N). Try this instead (untested):

   template <class T, class U>
   U const &
   get_value(std::map<T,U> const & _map, T const & _key)
   {
      typename std::map<T,U>::const_iterator it(_map.find(_key));
      if (it != _map.end())
      {
         return it->second;
      }
      throw std::domain_error("key not found");
   }

That is O log(N).

> And then when you want to use it :

   std::string const & s(get_value(lMapConst, "5"));

_____
Rob Stewart robert.stewart_at_[hidden]
Software Engineer, Core Software using std::disclaimer;
Susquehanna International Group, LLP http://www.sig.com

IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk