3 keys of an ordered map in C ++

I have a 3-component vector structure called Vector3 with 3 int , representing X, Y and Z. For each three-dimensional point (I have more or less than 200-300 different three-dimensional points) I have a string .

What I want to do is to have a data structure that checks for the presence of a string for this location. I wanted to use std::map and I made this code without good results:

The error is that it simply starts the else part once and continues to return the same string again and again.

My Vector3 class is the one that Ogre3D has: http://www.ogre3d.org/docs/api/html/classOgre_1_1Vector3.html

 String WorldGenerator::createPlatformBorder(Vector3 size) { static std::map<Vector3, String> generatedBorders; if (generatedBorders.find(size) != generatedBorders.end()) { return generatedBorders[size]; } else { String blockName = requestNewPlatformBorderName(); generatedBorders.insert(std::pair<Vector3, String>(size, blockName)); // some logic return blockName; } } 

Could you please help me?

Please note that the requestNewPlatformBorderName() function works fine, so there is no error. Here is the code for it:

 String requestNewPlatformBorderName() { static int counter = 0; return StringConverter::toString(++counter) + "-platform-border"; } 
+4
source share
2 answers

You have two alternatives:

  • Define the < operator for the Vector3 class or
  • Create a function that compares 2 Vector3 and will indicate it when declaring a map. This is especially useful when there is no natural (intuitive, ordinary, standard, etc.) Order for a class acting as a key, or when you want to order / match a criterion that is different from it. IMHO, the first case in your example, so I would be prone to this.

1. < operator

 bool operator < (const Vector3 &that) const { if( this.x != that.x ) return this.x < that.x ; else if( this.y != that.y ) return this.y < that.y ; else if( this.z != that.z ) return this.z < that.z ; else return false ; } 

2. Comparison Function

 class Vector3Comparator { public: bool operator () (const Vector3 &a,const Vector3 &b) const { if( ax != bx ) return ax < bx ; else if( ay != by ) return ay < by ; else if( az != bz ) return az < bz ; else return false ; } } ... static std::map<Vector3,string,Vector3Comparator> generatedBorders; 
+5
source

The Vector3 <operator is not suitable for use on a map. You need to define your own version.

 struct Vector3Cmp { bool operator()(const Vector3& v1, const Vector3& v2) { if (v1.x < v2.x) return true; if (v1.x > v2.x) return false; if (v1.y < v2.y) return true; if (v1.y > v2.y) return false; if (v1.z < v2.z) return true; if (v1.z > v2.z) return false; return false; } }; static std::map<Vector3, string, Vector3Cmp> generatedBorders; 
+2
source

Source: https://habr.com/ru/post/1499070/


All Articles