Skip to content

Instantly share code, notes, and snippets.

@bryangoodrich
Created July 24, 2015 22:39
Show Gist options
  • Save bryangoodrich/b63891bafa5d3f5dff18 to your computer and use it in GitHub Desktop.
Save bryangoodrich/b63891bafa5d3f5dff18 to your computer and use it in GitHub Desktop.
Sort an incoming map by key length, ties broken by string sorted order
/*********************************************************************
* Compilation: g++ -std=c++11 map.cpp -o map.exe
* Execution: map.exe < input.txt
*
* Output the contents of a sorted map
*
* This is a toy code snippet for using C++11 types to handle
* an input stream, store the incoming data columns by line,
* and sort the output list according to length of key,
* with ties broken by string sort order (map default).
*
* $ cat input.txt
* Jane 20
* John 40
* Joe 30
* Frank 50
*
* $ map.exe < input.txt
* Input Map ...
* <name: Joe, age: 30>
* <name: Jane, age: 20>
* <name: John, age: 40>
* <name: Frank, age: 50>
*********************************************************************/
#include <iostream> // std::cout, std::cin
#include <string> // std::string
#include <map> // std::map
struct cmp_by_length
{
bool operator( )(const std::string& a, const std::string& b) const
{
if (a.length() < b.length())
return true;
else if (a.length() == b.length())
return a < b;
else false;
}
};
int main( )
{
std::map<std::string, int, cmp_by_length> m;
std::string key;
int value;
while (std::cin >> key >> value)
{
m[key] = value;
}
std::cout << "Input Map ..." << std::endl;
for (auto itr = m.begin(), end = m.end(); itr != end; ++itr)
{
std::cout << "<name: " << itr->first;
std::cout << ", age: " << itr->second;
std::cout << ">" << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment