STL map 的 key 元素

在做 compiler 语义分析时, 需要用到 map<?,?>

在别人的代码上做扩展, 所以有些代码是不能动的

这时, 需要一个 map<symbol,int> 的数据结构, 但是我并不清楚 symbol 是否重载了 <

我特地试了一下, 没有重载 '<' 的新类, 使用 map 是要报错的

 

改用 map<symbol*,int>, 成功了

#include <iostream>
#include <map>
using namespace std;

class unknow {
private:
	int index;
public:
	int get_index() {
		return index;
	}
	void increment() {
		index++;
	}
	/*
	bool operator<(const unknow &other) const {
		return this->index < other.index;
	}
	*/
};

int main() {
	map<unknow*, int> mapping;
	unknow *u1 = new unknow();
	unknow *u2 = new unknow();
	unknow *u3 = new unknow();
	mapping[u1] = 1;
	mapping[u2] = 2;
	mapping[u3] = 3;
	cout << u1 << endl;
	cout << u2 << endl;
	cout << u3 << endl;

	return 0;
}

  

上面的代码, 使用 map<unknow,int> 会报错的

我想, 使用指针的话, 排序应该是按照地址来的, 不过想不出什么办法去验证

另外, 有一个问题困扰我很久了, 就是一一对应的数据结构的实现, 以前在做 coursera 算法作业时就需要一一对应, 当初专门去论坛问了下, 得知只能用 map<A,B>, map<B,A>, 这种实现实在太过粗糙, 弊端很多

posted @ 2014-01-17 20:17  SangS  阅读(1164)  评论(0编辑  收藏  举报