Skip to content

Instantly share code, notes, and snippets.

@alifarazz
Last active April 3, 2021 01:59
Show Gist options
  • Save alifarazz/93f3dabe46510b32183971dda7f9e991 to your computer and use it in GitHub Desktop.
Save alifarazz/93f3dabe46510b32183971dda7f9e991 to your computer and use it in GitHub Desktop.
Sort a struct of arrays using an extra array as indexer (therefore, with one level of indirection)
#include <algorithm>
#include <array>
#include <iostream>
#include <random>
#include <string_view>
const int LEN = 10;
using Indexer = int;
class SOA
{
public:
std::array<int, LEN> propA;
std::array<int, LEN> propB;
std::array<int, LEN> propC;
std::array<int, LEN> propD;
std::array<Indexer, LEN> indexIndirct;
explicit SOA()
{
for (int i = 0; i < LEN; i++)
propA[i] = propB[i] = propC[i] = propD[i] = indexIndirct[Indexer(i)] = i;
print("Init\t");
}
auto shuffle(std::mt19937& gen) -> void
{
std::ranges::shuffle(propA, gen);
std::ranges::shuffle(propB, gen);
std::ranges::shuffle(propC, gen);
std::ranges::shuffle(propD, gen);
std::ranges::shuffle(indexIndirct, gen);
print("Shuffle\t");
}
auto sortByA() -> void
{
auto cmp = [this](const Indexer& a, const Indexer& b) {
return propA[a] < propA[b];
};
std::sort(indexIndirct.begin(), indexIndirct.end(), cmp);
}
auto sortByB() -> void
{
auto cmp = [this](const Indexer& a, const Indexer& b) {
return propB[a] < propB[b];
};
std::sort(indexIndirct.begin(), indexIndirct.end(), cmp);
}
auto print(std::string_view sv) -> void
{
std::cout << sv << '\t';
print();
}
auto print() -> void
{
std::cout << "A: [";
for (int i = 0; i < LEN; i++)
std::cout << propA[indexIndirct[i]] << ", ";
std::cout << "\b\b], B: [";
for (int i = 0; i < LEN; i++)
std::cout << propB[indexIndirct[i]] << ", ";
std::cout << "\b\b]\n";
}
};
SOA soa;
int
main()
{
std::random_device rd;
std::mt19937 gen{ rd() };
soa.shuffle(gen);
soa.sortByA();
soa.print("Sort By A");
soa.sortByB();
soa.print("Sort By B");
}
///OUTPUT/////////////////////////////////////////////////////////////////////////////////
// Init A: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], B: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] //
// Shuffle A: [1, 4, 2, 3, 5, 8, 0, 9, 6, 7], B: [6, 8, 0, 9, 5, 4, 1, 2, 3, 7] //
// Sort By A A: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], B: [1, 6, 0, 9, 8, 5, 3, 7, 4, 2] //
// Sort By B A: [2, 0, 9, 6, 8, 5, 1, 7, 4, 3], B: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] //
//////////////////////////////////////////////////////////////////////////////////////////
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment