#include <iostream>
#include <algorithm>
#include <vector>
#include <utility>
#include <string>
#include <map>
using namespace std;
void PrintPair(const std::pair<int, std::string>& thePair)
{
std::cout << thePair.first << ", " << thePair.second << std::endl;
}
int main() {
// create our vector
std::vector<std::pair<int, std::string>> myVector{
std::make_pair(10,"bcd"),
std::make_pair(2, "abc"),
std::make_pair(30, "def"),
std::make_pair(2, "xyz"),
std::make_pair(50, "mn")
};
// print vector before sorting
std::cout << "vector before sorting:\n";
for (auto&& nextPair : myVector)
{
std::cout << nextPair.first << ", " << nextPair.second << std::endl;
}
// sort it on the ints in the pairs
std::stable_sort(std::begin(myVector),std::end(myVector), [](const std::pair<int,std::string>& lhs, const std::pair<int,std::string>& rhs){return lhs.first < rhs.first;});
// print vector after sorting
std::cout << "\nvector after sorting\n";
for (auto&& nextPair : myVector)
{
std::cout << nextPair.first << ", " << nextPair.second << std::endl;
}
std::map<int, decltype(myVector)> myBuckets;
for (auto&& nextElement : myVector)
{
if (myBuckets.find(nextElement.first) == myBuckets.end())
myBuckets[nextElement.first] = decltype(myVector){nextElement};
else
myBuckets[nextElement.first].emplace_back(nextElement);
}
//needs at least a 2 element vector to work
cout << "\nFinal output:\n";
// create buckets for each value, internally each bucket is stable sorted
// the buckets are sorted on map value
// print out each element in a bucket before moving onto the next bucket
auto bucketsBegin = myBuckets.begin();
auto bucketsEnd = myBuckets.end();
--bucketsEnd;
auto nextEndElement = bucketsEnd->second.begin();
auto nextBeginElement = bucketsBegin->second.begin();
while(bucketsBegin != myBuckets.end() && bucketsBegin != bucketsEnd)
{
if (bucketsEnd != bucketsBegin)
{
PrintPair(*nextEndElement);
++nextEndElement;
if (nextEndElement == bucketsEnd->second.end())
{
bucketsEnd--;
nextEndElement = bucketsEnd->second.begin();
}
}
PrintPair(*nextBeginElement);
++nextBeginElement;
if (nextBeginElement == bucketsBegin->second.end())
{
bucketsBegin++;
if (bucketsBegin != myBuckets.end())
nextBeginElement = bucketsBegin->second.begin();
}
}
//print remainder
while(nextBeginElement != bucketsBegin->second.end())
{
PrintPair(*nextBeginElement);
++nextBeginElement;
}
return 0;
}