C 样式字符串键上的 multimap 无法插入条目 [英] multimap on C-style string key fails to insert entries

查看:21
本文介绍了C 样式字符串键上的 multimap 无法插入条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个以 C 样式字符串为索引的多映射,如以下代码段所示:

I am trying to create a multimap indexed on a C-style string, as shown in the following code segment:

    #include <cstring>
    #include <map>
    #include <iostream>

    using namespace std;

    int main(void)
    {
        int i, j;
        int (*fn_pt)(const char *, const char *) = strcmp;
        multimap<char *, char *, int (*)(const char *, const char *)>a(fn_pt);

        for (i = 0; i < 2; i++)
        {
            char key[2];
            sprintf(key, "%d", i);
            for (j = 0; j< 5; j++)
            {
                char value[2];
                sprintf(value, "%d", j);
                a.insert(pair<char *, char *>(key, value));
            }
        }

        for (i = 0; i < 2; i++)
        {
            char key[2];
            sprintf(key, "%d", i);
            multimap<char *, char *>::iterator it = a.find(key);
            while (it != a.end())
            {
                cout << it->first << "\t" << it->second <<endl;
                it++;
            }
        }
    }

只需将上述程序中的键更改为整数即可得到预期的结果.但是,在字符串上索引 multimap 给了我一些意想不到的东西(只有 1 和 4 的行由空格分隔),而不是显示我使用的每个键值的每个值.

Simply changing the key in the above program to integer gives me the expected result. But, indexing the multimap on a string is giving me something unexpected (only rows of 1's and 4's separated by space), instead of showing me every value for every key value used.

我哪里出错了?

谢谢

推荐答案

strcmp 是在 multimap 中使用的错误谓词.谓词应满足以下条件:

strcmp is a wrong predicate to use in multimap. The predicate shall satisfy the following:

表达式 comp(a,b),其中 comp 是此比较类的对象,a 和 b 是键值,如果在严格弱排序操作中将 a 放在比 b 更早的位置,则应返回 true.

The expression comp(a,b), where comp is an object of this comparison class and a and b are key values, shall return true if a is to be placed at an earlier position than b in a strict weak ordering operation.

strcmp 违反了这一点,因为如果字符串不相等,它会返回一个非零值,要么是 <b 或 a > b.

strcmp violates that because it returns a nonzero value if the strings are unequal, either a < b or a > b.

您应该定义自己的谓词,该谓词返回 true 当且仅当第一个字符串小于第二个字符串.

You should define your own predicate which returns true if and only if the first string is less than the second.

这篇关于C 样式字符串键上的 multimap 无法插入条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆