Created
July 16, 2011 18:40
-
-
Save pyrtsa/1086628 to your computer and use it in GitHub Desktop.
std::map using string keys compared backwards
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
map contents in order: | |
- three: 3 | |
- one: 1 | |
- two: 2 | |
- four: 4 | |
map["three"]: 3 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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