|
Boost : |
Subject: [boost] Re : BOOST_FOREACH like macro for map
From: Pierre Morcello (pmorcell-cppfrance_at_[hidden])
Date: 2009-10-20 16:50:39
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 :
[code]
#include <boost/foreach.hpp>
#include <stdexcept>
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)
{
return lPair.second;
}
}
throw std::domain_error("[ConstMapHelper::getConst] key not found"); // do what you want
}
};
[/code]
And then when you want to use it :
// construction of the const map
std::map<std::string, std::string> lMap;
lMap.insert(std::make_pair("1","1"));
lMap.insert(std::make_pair("2","2"));
const std::map<std::string, std::string> lMapConst(lMap);
// access
const std::string key = "5"; // the key
const std::string& s = ConstMapHelper::getConst(key,lMapConst); // will throw exception because "5" is not in the map.
You can even make it a true one liner if you get rid of the reference in the 'key' parameter.
Hope this helps,
Best regards,
Pierre Morcello
--- En date de : Mar 20.10.09, mobi phil <mobi_at_[hidden]> a écrit :
> De: mobi phil <mobi_at_[hidden]>
> Objet: [boost] BOOST_FOREACH like macro for map
> À: boost_at_[hidden]
> Date: Mardi 20 Octobre 2009, 9h06
> Hello,
>
> new to this list... did not find anything similar on net.
>
> 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.
>
>
> given the map
>
> const map<string, string> aStringMap;
>
> I cannot write
>
> const string &s = aStringMap["key"];
> process(s);
>
> I should write:
>
> map<string, string>::const_iterator
> it=aStringMap..find("key")
> if( it != aStringMap.end() ) {
> process(it->second)
> }
>
> so would be nice to have a macro like
>
> BOOST_CONSTMAPFIND(aStringMap, "key", data)
> {
> processResult( data );
> }
>
> the version
>
> if(BOOST_CONSTMAPFIND(l_map, l_key, l_data) )
> {
>
> }
>
> Seems to be impossible to implement
>
>
> --
> rgrds,
> mobi phil
>
> being mobile, but including technology
> http://mobiphil.com
> _______________________________________________
> Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
>
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk