1

我想对字符串进行排序。最简单的方法是将所有足够的东西放入地图中。为了有效地使用内存,我将后缀传递为 (str+i),其中 str 是 char*,i 是位置后缀开头。但是,我发现 map 不足以对这些进行排序。这是一个例子

typedef std::map < char*, int,Comparator> MapType;
MapType data;

// let's declare some initial values to this map
char* bob=(char* )"Bobs score";
char* marty=(char* ) "Martys score";
data.insert(pair<char*,int>(marty+1,15));
data.insert(pair<char*,int>(bob+1,10));
MapType::iterator end = data.end();
for (MapType::iterator it = data.begin(); it != end; ++it) {
    std::cout << "Who(key = first): " << it->first;
    std::cout << " Score(value = second): " << it->second << '\n';
}

输出是

    Who(key = first): obs 得分 Score(value = second): 10
    Who(key = first): artys score(value = second): 15

但是,strcmp用于比较字符串的标准函数对于 bob+1 和 marty+1 可以正常工作。它说 marty+1 小于 bob+1。

4

3 回答 3

5

将按的map地址排序char*,而不是按字典顺序排序。将键更改为 astd::string或定义比较器。

编辑:

看起来好像您已尝试定义 aComparator但未发布它的定义。这是一个例子:

#include <iostream>
#include <map>
#include <string.h>

struct cstring_compare
{
    bool operator()(const char* a_1, const char* a_2) const
    {
        return strcmp(a_1, a_2) < 0;
    }
};

typedef std::map<const char*, int, cstring_compare> cstring_map;

int main()
{
    cstring_map m;

    m["bcd"] = 1;
    m["acd"] = 1;
    m["abc"] = 1;

    for (cstring_map::iterator i =  m.begin(); i != m.end(); i++)
    {
        std::cout << i->first << "\n";
    }

    return 0;
}

输出:

美国广播公司
acd
bcd
于 2012-05-01T09:10:40.647 回答
0

定义一个自定义比较器,例如

class compare_char { 
   public:
      bool operator()(const char* lhs, const char* rhs) { return strcmp(lhs, rhs); } 
};

使用此比较器而不是您当前拥有的任何东西来定义您的地图。或者,使用具有与值一起使用的比较运算符的键类型的映射, std::string 更适合您。目前,您有一个使用 char* 作为比较 char* 类型的键的地图,即。指针的值,而不是内容。

于 2012-05-01T09:30:12.983 回答
0

您应该添加您正在使用的比较器类或函数,因为这可能是您的错误的来源。
strcmp 和地图比较函数之间存在细微差别。

如果 a == b,strcmp 返回 0,如果 a < b,则返回 -1,如果 a > b 则返回 1
comp 返回 true 是 a < b,否则返回 false。

实现比较功能的正确方法如下:

bool operator() (char* lhs, char* rhs) const
{
        return strcmp(lhs,rhs) < 0;
}
于 2012-05-01T09:32:58.463 回答