Skip to content

Instantly share code, notes, and snippets.

@pyrtsa
Created July 16, 2011 18:40
Show Gist options
  • Save pyrtsa/1086628 to your computer and use it in GitHub Desktop.
Save pyrtsa/1086628 to your computer and use it in GitHub Desktop.
std::map using string keys compared backwards
map contents in order:
- three: 3
- one: 1
- two: 2
- four: 4
map["three"]: 3
#include <algorithm>
#include <map>
#include <string>
template <typename T> struct reverse_compare {
bool operator()(T const & a, T const & b) const {
return std::lexicographical_compare(a.rbegin(), a.rend(),
b.rbegin(), b.rend());
}
};
int main() {
typedef std::map<std::string, int,
reverse_compare<std::string> > reverse_map;
reverse_map map;
map["one"] = 1;
map["two"] = 2;
map["three"] = 3;
map["four"] = 4;
std::cout << "map contents in order:" << std::endl;
for (reverse_map::const_iterator i = map.begin(), e = map.end(); i != e; ++i)
std::cout << " - " << i->first << ": " << i->second << std::endl;
std::cout << "map[\"three\"]: " << map["three"] << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment