问题中“ID”的定义不是很清楚:您是否需要将其用作快速顶点查找的键?您可以定义一个比较器std::map
(参见下面的示例)
您是否需要能够区分具有相同坐标(但在另一个字段中不同)的两个 Vertex 对象?定义一些“id 工厂”(参见单例模式),它生成例如与 Vertex 对象的值无关的整数序列。- 与 Fire Lancer 建议的方式很相似(但要注意线程安全问题!)
在我看来,具有相同坐标的两个顶点是相同的。那么为什么你甚至需要一个额外的ID呢?
只要您在此类型上定义了“严格弱排序”,您就可以将其用作例如 an 中的键std::map
,
struct Vertex {
typedef short int Value;
Value v1, v2;
bool operator<( const Vertex& other ) const {
return v1 < other.v1 || ( v1 == other.v1 && v2 < other.v2 ) ;
};
Vertex x1 = { 1, 2 };
Vertex x2 = { 1, 3 };
Vertex y1 = { 1, 2 }; // too!
typedef std::set<Vertex> t_vertices;
t_vertices vertices;
vertices.insert( x1 );
vertices.insert( x2 );
vertices.insert( y1 ); // won't do a thing since { 1, 2 } is already in the set.
typedef std::map<Vertex, int> t_vertex_to_counter;
t_vertex_to_counter count;
count[ x1 ]++;
assert( count[x1] == 1 );
assert( count[y1] == 1 );
count[ x2 ]++;
count[ y1 ]++;
assert( count[x1] == 2 );
assert( count[y1] == 2 );