-4

I have created the following comparator to test the map:

struct comparator{
    bool operatior() (int a,int b){
        return 1;
    }
}

then the following algorthim:

int main(){
    // imports string to currentString
       ...
    std::map<int,char> default_map;
    std::map<int,char,comparator> test_map;

    while(i < stringSize){
       if(currentString[i] == '(' || currentString[i] == ')'){
          default_map[i]=currentString[i];
          test_map[i]=currentString[i];
       }
    }

    auto currentIterator = default_map.begin();
    while(currentIterator != default_map.end()){
        printf("%d %c\n",currentIterator->first,currentIterator->second);
    }

    auto currentIterator = test_map.begin();
    while(currentIterator != test_map.end()){
         printf("%d %c\n",currentIterator->first,currentIterator->second);
    }

    return 0;
}

Here the default_map prints all of the parenthesis, while the test_map with the custom comparitor only prints the first two parenthesis.

Is this a bug in the map code? I originally wanted to have class as the key with a custom comparator, but it isn't even working with a custom int key.

My make file does use the -std=c++1y tag so maybe that is effecting it? I don't know what to do. I am considering to see if the SGI map will work better than the std one.

2 Answers2

1

You need to implement the compare function correctly.

struct comparator{
    bool operatior() (int a,int b){
        return (a < b);
        // return 1;
    }
}

Otherwise, it does not meet the criteria for ordering the keys of the map.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

Your "comparator" (with incorrectly spelled "operator") always returns 1. How do you expect that to usefully determine if something is already in the map or its correct ordering? (Hint: it won't).

You need to write a function that actually compares elements in a useful way.

The comparison function needs to implement a strict weak ordering to be usable in a map.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • Thank you. I was doing something like this for the comparator: if(a > b) return 1; else if (a==b) return 0; else return -1; – Henrickunit Jun 12 '17 at 20:31
  • Well what happens if two elements are equal??? I guess it just switches a and b to check for that. Okay makes sense. – Henrickunit Jun 12 '17 at 20:33