一个数组保存了N个结构,每个结构保存了一个坐标,结构间的坐标都不相同,请问如何找到指定坐标的结构(除了遍历整个数组,是否有更好的办法)?

#include 
#include 
using namespace std;

#define N 5

typedef struct pointer {
	int x;
	int y;
	//map对插入元素自动排序,使用时必须重写结构体的<操作函数
	bool operator<(pointer const& p) const {
		if (x < p.x) {
			return true;
		} else if (x > p.x) {
			return false;
		}
		return y < p.y;
	}
} Pointer;

void init(Pointer* pointers, int len, map& pointMap) {
	for (int i = 0; i < len; ++i) {
		pointMap.insert(pair(pointers[i], i));
	}
}

void readAll(Pointer* pointers, int len, map pointMap) {
	for (int i = 0; i < len; ++i) {
		//用结构体查找,注意查找语法
		map::iterator pointer = pointMap.find(pointers[i]);
		if (pointer != pointMap.end()) {
			cout << "( " << pointer->first.x << " , " << pointer->first.y
					<< " )" << " index: " << pointer->second << endl;
		}
	}
}
bool findPointer(map pointMap, int len, Pointer pointer,
		Pointer &result) {
	map::iterator iter = pointMap.find(pointer);
	if (iter != pointMap.end()) {
		cout << "( " << iter->first.x << " , " << iter->first.y << " )"
				<< " index: " << iter->second << endl;
		result = iter->first;
		return true;
	}
	return false;
}

int main() {
	Pointer pointers[] = { { 1, 2 }, { 2, 4 }, { 4, 4 }, { 1, 5 }, { 2, 7 }, {
			9, 9 }, { 3, 5 }, { 3, 4 } };

	map pointMap;
	int len = sizeof(pointers) / sizeof(Pointer);

	init(pointers, len, pointMap);
	readAll(pointers, len, pointMap);

	Pointer result;
	if (findPointer(pointMap, len, pointers[2], result)) {
		cout << "result: " << "( " << result.x << " , " << result.y << " )"
				<< endl;
	}
	return 0;
}

你可能感兴趣的:(算法-数组)