Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSString as key in Objective-C++ std::map

I'm starting work on an Objective-C++ project, getting a feel for how the synthesis of the two languages feels before I do any heavy-duty design. I am very intrigued by how Automated Reference Counting has been integrated with C++: we get the equivalent of smart pointers for NSObjects that handle retain/release properly in STL containers (cf. David Chisnall's article at http://www.informit.com/articles/article.aspx?p=1745876&seqNum=3).

I want to use STL map as a typesafe mapping from NSStrings to C++ values. I can declare a mapping as

std::map<NSString*, MyType> mapping

With ARC, this mapping handles the memory management properly. But it doesn't follow NSString value semantics properly, because it's using pointer comparisons instead of -[NSString compare:].

What's the best way to get an STL map to use string comparison instead of pointer comparison?
Should I try to specialize std::less<NSString*>?
Should I declare an explicit comparator like std::map<NSString*, MyType, MyCompare>?
Should I wrap the NSString* keys in a smart pointer that implements operator<?

like image 360
Jay Lieske Avatar asked Jan 20 '12 18:01

Jay Lieske


1 Answers

You'd want a custom comparison object that calls NSString's compare function, something like this:

#include <functional>
#include <map>

struct CompareNSString: public std::binary_function<NSString*, NSString*, bool> {
    bool operator()(NSString* lhs, NSString* rhs) const {
        if (rhs != nil)
            return (lhs == nil) || ([lhs compare: rhs] == NSOrderedAscending);
        else
            return false;
    }
};

std::map<NSString*, MyType, CompareNSString> mapping;
like image 183
Ross Smith Avatar answered Nov 20 '22 02:11

Ross Smith