我想排序一个字符串的足够.最简单的方法是将所有足够的东西放入地图中.为了有效地使用内存,我将后缀作为(str + i)传递,其中str是char*,i是以后缀开头的位置.但是,我发现地图不会对这些东西进行排序.这是一个例子
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';
}
Run Code Online (Sandbox Code Playgroud)
输出是
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*,不lexiographically.将密钥更改为a 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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
abc acd bcd
| 归档时间: |
|
| 查看次数: |
220 次 |
| 最近记录: |