gpt4 book ai didi

c++ - 映射和子字符串

转载 作者:行者123 更新时间:2023-11-30 01:26:27 25 4
gpt4 key购买 nike

我想对一个字符串进行排序。最简单的方法是将所有的 suffices 放入 map 中。为了有效地使用内存,我将后缀作为 (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 Score(value = second): 10    Who(key = first): artys score Score(value = second): 15

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

最佳答案

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

编辑:

看起来好像您试图定义一个 Comparator 但它的定义没有发布。这是一个例子:

#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;
}

输出:

abcacdbcd

关于c++ - 映射和子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10395651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com