stl map 复合型主键怎么搞定?

tkminigame 2009-07-05 07:37:29
比如一个结构是这样的。
struct A{
int a;
int b;
}
怎么样用它做键值?不要用指针。
...全文
222 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
map以自定义类型为主键,只需要重载<运算符。

http://www.cnblogs.com/kevintian/articles/1277700.html
baihacker 2009-07-05
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 tkminigame 的回复:]
引用 5 楼 baihacker 的回复:
引用 4 楼 tkminigame 的回复:
引用 1 楼 baihacker 的回复:
C/C++ code写一个
bool operator < (const A& x, const A& y)
{
}
然后
map <A, 其它值>
就行了.


error C2804: binary 'operator <' has too many parameters


C/C++ code定义为友元
struct A
{
friend bool operator < (cosnt A& ,const A&);
};
bool operator < (cosnt A& x,const A& y)
{

[/Quote]
一般是return x.a < y.a || x.a == y.a && x.b < y.b;
老邓 2009-07-05
  • 打赏
  • 举报
回复
自定义结构体,需要重载<,就可以做key了,2楼错了
tkminigame 2009-07-05
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 baihacker 的回复:]
引用 4 楼 tkminigame 的回复:
引用 1 楼 baihacker 的回复:
C/C++ code写一个
bool operator < (const A& x, const A& y)
{
}
然后
map <A, 其它值>
就行了.


error C2804: binary 'operator <' has too many parameters



C/C++ code定义为友元
struct A
{
friend bool operator < (cosnt A& ,const A&);
};
bool operator < (cosnt A& x,const A& y)
{
}
[/Quote]
方法里面这样写可不可行?
return (&obj1<&obj2);
老邓 2009-07-05
  • 打赏
  • 举报
回复
include <stdlib.h>
#include <stdio.h>
#include <map>
#include <string>

using namespace std;

struct A{
int a;
int b;

bool operator < ( const A rhs) const {return a < rhs.a;}
};

int main()
{
map<A, string> m;
A a = {1, 2};
m.insert(pair<A, string>(a, "ok"));
system( "pause" );
return 0;
}
tkminigame 2009-07-05
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 Loaden 的回复:]
key必需为一内置类型,不能是对象!
[/Quote]
那怎么搞定。
baihacker 2009-07-05
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 tkminigame 的回复:]
引用 1 楼 baihacker 的回复:
C/C++ code写一个
bool operator < (const A& x, const A& y)
{
}
然后
map <A, 其它值>
就行了.



error C2804: binary 'operator <' has too many parameters
[/Quote]
定义为友元
struct A
{
friend bool operator < (cosnt A& ,const A&);
};
bool operator < (cosnt A& x,const A& y)
{
}
tkminigame 2009-07-05
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 baihacker 的回复:]
C/C++ code写一个
bool operator < (const A& x, const A& y)
{
}
然后
map<A, 其它值>
就行了.
[/Quote]

error C2804: binary 'operator <' has too many parameters
大前置 2009-07-05
  • 打赏
  • 举报
回复
引用

附带有指针功能,比较可靠,不用担心内存问题。
老邓 2009-07-05
  • 打赏
  • 举报
回复
key必需为一内置类型,不能是对象!
baihacker 2009-07-05
  • 打赏
  • 举报
回复
写一个
bool operator < (const A& x, const A& y)
{
}
然后
map<A, 其它值>
就行了.

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧