I'm having an issue porting my functor from windows to linux. (a functor to pass to stl::map for strict-weak ordering) The original is as follows:
struct stringCompare{ // Utilized as a functor for stl::map parameter for strings
bool operator() (string lhs, string rhs){ // Returns true if lhs < rhs
if(_stricmp(lhs.c_str(), rhs.c_str()) < 0) return true;
else return false;
}
};
As linux doesnt support _stricmp but uses strcasecmp instead, I changed it to:
struct stringCompare{
bool operator() (string lhs, string rhs){ // Returns true if lhs < rhs
if(strcasecmp(lhs.c_str(), rhs.c_str()) < 0) return true;
else return false;
}
};
And it is now complaining about "const" parameters:
passing const stringCompare as this argument of bool stringCompare::operator()
(std::string, std::string)â discards qualifiers
I'm not entirely sure why it supposes stringCompare should be a constant...
And the line where it is mad about this being instantiated is:
if(masterList->artistMap.count(songArtist) == 0)
artistMap being an stl::map with a string key.
I'm not sure where I'm going wrong. I attempted to change the bool operator() parameters to const, as it appears that it's complaining about some sort of non-constant parameter passing. This didn't work, nor did changing 'bool operator()' to 'const bool operator()'.
As far as I know, strcasecmp is a const function so should case whether I pass it non-constant or constant parameters (c_str() also being const), so I'm not exactly certain where I'm going wrong.
I've googled similar issues but I still can't quite make sense of the issue from what I've seen both on stackoverflow and a couple other places.
The datatype where I'm using this is:
map<string, set<song, setSongCompare>*,stringCompare > artistMap;
Two things:
Define your bool operator()
as const
. It's just a good practice. This tells the compiler that this function will not have side-effects on the member variables of the class.
Add const &
qualifiers to the lhs
and rhs
arguments. Passing constant references instead of copying memory all over the place is also good practice. By declaring references as const
you're telling compiler that this function should not have side-effects on the referenced objects.
Your operator()
should look as follows:
bool operator() (const string &lhs, const string &rhs) const
{
return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With