有没有办法让 std::map 来“编辑”像键的谓词这样的值?

发布于 2024-10-08 19:36:32 字数 385 浏览 0 评论 0原文

我想知道是否可以为 std::map 的所有值创建类似谓词的东西,这样我就不必在将它们插入映射之前编辑这些值。

我想要的是这样的:

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

上下文是我正在为 .ini 文件创建一个 std::map 并且当我想要检索它们时,我希望它自动从值中删除前导/尾随空格< /强>。我已经创建了一个谓词来忽略键中的大小写和空格,因此我想知道是否可以对值执行相同的操作。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

东走西顾 2024-10-15 19:36:32

我认为你必须遵循超载原则才能达到预期的目标,
尝试这个选项,

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

其中,

class tMap
{
        public:

                map<mystring,string> _tMap;

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

};

mystring 又是一个可以重载“==”运算符进行修剪的类。
我知道地图可以作为类(包装器)实现,然后用于实现所需的结果。也许再多努力一点就能解决这个问题。

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.

演多会厌 2024-10-15 19:36:32

您可以有一个包装器类,它包装 std::string 并可

  1. std::string 隐式构造,
  2. 实现来自 std::string 的转换运算符>。

您可以在这两个函数中即时编辑该值。 std::map 可以将包装器作为键。

话虽如此,与其聪明一点,不如更明确一点,并拥有一个带有自己的 get/set 接口的单独的 INI 类。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文