Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3 keys ordered map in C++

Tags:

c++

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

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

The error it has is that It just runs the else part once, and keeps returning the same string over and over.

My Vector3 class is the one in Ogre3D: 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 help me out, please?

Note that the function requestNewPlatformBorderName() works perfectly fine, so the bug isn't there. Here is the code for it:

String requestNewPlatformBorderName()
{
    static int counter = 0;
    return StringConverter::toString(++counter) + "-platform-border";
}
like image 729
Pacha Avatar asked Mar 22 '23 15:03

Pacha


1 Answers

You have two alternatives:

  1. Define the < operator for class Vector3, or
  2. Create a function that compares 2 Vector3s and specify it when declaring the map. This one is particularly useful when there is no natural (intuitive, common, default, etc) ordering for the class acting as key, or when you want to order/map by a criterion different than it. IMHO, the first is the case in your example, so I would be inclined for it.

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( a.x != b.x )
            return a.x < b.x ;
        else if( a.y != b.y )
            return a.y < b.y ;
        else if( a.z != b.z )
            return a.z < b.z ;
        else
            return false ;
    }
}
...
static std::map<Vector3,string,Vector3Comparator> generatedBorders;
like image 64
Mario Rossi Avatar answered Apr 19 '23 04:04

Mario Rossi