开发者

Is there a way for std::map to "edit" values like a predicate for the key?

I am wondering if it is possible to create something like a predicate for a std::map for all of its values so I don't have to edit the values before I insert them into the map.

What I would like is something like this:

mymap["username"] = " Marlon "; // notice the space on both sides of my name
assert(mymap["username"] == "Marlon"); // no more whitespace

The context is I am creating a std::map for a .ini file and I would like it to automatically remove leading/trailing whitespace from the values when I want to retrieve th开发者_Go百科em. I've already created a predicate to ignore casing and whitespace from the key so I want to know if it is possible to do the same for the value.


I think you must follow the overloading principles to achieve the desired objective, Try this option,

//map<string,string> testMap; Old Map definition
tMap testMap;

Where,

class tMap
{
        public:

                map<mystring,string> _tMap;

                mystring& operator [] (const char *index)
                {
                        return _tMap[index];
                }

};

mystring again is a class which can be overloaded for '==' operator for trimming.
I know maps can be implemented as a class (Wrapper) and then used to achieve the desired result. May be a bit more effort would solve this problem.


You can have a wrapper class that wraps std::string and

  1. is implicitly constructible from std::string
  2. implements a conversion operator from std::string.

You can edit the value on the fly in either of these functions. You std::map can hen have the wrapper as a key.

With that said, it's still better being a little more explicit, than clever, and have a separate INI class with its own get/set interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜