3

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 them. 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.

Marlon
  • 19,924
  • 12
  • 70
  • 101
  • Trim the values either when you insert or retrieve them? http://stackoverflow.com/questions/122616/painless-way-to-trim-leadingtrailing-whitespace-in-c – moinudin Dec 25 '10 at 01:39
  • Not to be rude, but for the sake of the question I am asking please read what I wrote in bold. – Marlon Dec 25 '10 at 01:43
  • Why do you want this? Is it so bad to modify them before insertion? – asveikau Dec 25 '10 at 02:04
  • To know if it is possible in C++. Isn't it good to know the capabilities of a language? :D – Marlon Dec 25 '10 at 02:34
  • 1
    C++ can do a lot of things. It doesn't make it a good idea. (As to ascertaining a language's capabilities, I'd say knowing it's Turing complete should be enough... :-)) – asveikau Dec 25 '10 at 03:05

2 Answers2

2

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.

kumar_m_kiran
  • 3,982
  • 4
  • 47
  • 72
1

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.

Alex B
  • 82,554
  • 44
  • 203
  • 280