Pointers can be used as keys but especially with a std::map (or std::set) I would not advise it. The behavior of the program is not deterministic i.e. when one iterates over the map the order in which the items in the map are iterated is not guaranteed to be the same. It really depends on the memory address of the object (key). Take a look at this example, as you can see irrespective of the insertion order into the map the items are iterated in a deterministic way when the key is a string rather than a pointer.
http://ideone.com/VKirct
#include <iostream>
#include <map>
using namespace std;
class SomeClass {
public:
SomeClass(const std::string& name): m_name(name) {}
std::string GetName()const {return m_name; }
bool operator <(const SomeClass& rhs) const { return m_name < rhs.m_name; }
private:
std::string m_name;
};
auto print_seq = [](const auto& seq) { for (const auto& itr: seq) {std::cout << itr.second << " , ";} std::cout << std::endl;};
int main() {
// your code goes here
std::map<SomeClass*, std::string> pointer_keyed_map;
SomeClass s3("object3");
SomeClass s1("object1");
SomeClass s2("object2");
pointer_keyed_map.insert(std::make_pair(&s1, s1.GetName()));
pointer_keyed_map.insert(std::make_pair(&s2, s2.GetName()));
pointer_keyed_map.insert(std::make_pair(&s3, s3.GetName()));
std::cout << "Pointer based keys: object order" << std::endl;
print_seq(pointer_keyed_map);
std::map<SomeClass, std::string> int_keyed_map;
int_keyed_map.insert(std::make_pair(s3, s3.GetName()));
int_keyed_map.insert(std::make_pair(s1, s1.GetName()));
int_keyed_map.insert(std::make_pair(s2, s2.GetName()));
std::cout << "String based keys: object order" << std::endl;
print_seq(int_keyed_map);
return 0;
}
less<T>
can be used in a map. See #1099466 – Transarctic