Skip to content
Permalink
Browse files

Merge pull request #17 from lkundrak/lr-sort

SortableVector: avoid qsort()ing C++ objects
  • Loading branch information...
thp committed Jan 31, 2016
2 parents c0abd47 + 3ef95f3 commit e9bd8b52bac90df706a6b68c6a1cd8076fcec6c7
Showing with 27 additions and 25 deletions.
  1. +23 −8 src/Levels.cpp
  2. +4 −17 src/Levels.h
@@ -27,6 +27,7 @@

#include <iostream>
#include <string>
#include <algorithm>


static const char MISC_COLLECTION[] = "C99_My Levels";
@@ -99,16 +100,30 @@ compare_names(const std::string &a, const std::string &b)
return ma[2].compare(mb[2]);
}

int
LevelDesc::compare(const LevelDesc *a, const LevelDesc *b)
bool
operator<(LevelDesc a, LevelDesc b)
{
return compare_names(a->file, b->file);
return compare_names(a.file, b.file) < 0;
}

int
Collection::compare(const Collection *a, const Collection *b)
void
LevelDesc::swap(LevelDesc &a, LevelDesc &b)
{
std::swap(a.file, b.file);
}

bool
operator<(Collection a, Collection b)
{
return compare_names(a.name, b.name) < 0;
}

void
Collection::swap(Collection &a, Collection &b)
{
return compare_names(a->name, b->name);
std::swap(a.file, b.file);
std::swap(a.name, b.name);
std::swap(a.levels, b.levels);
}

Levels::Levels(std::vector<std::string> dirs)
@@ -242,9 +257,9 @@ std::string Levels::levelName( int i, bool pretty )
void
Levels::sort()
{
m_collections.sort();
std::sort(m_collections.begin(), m_collections.end());
for (auto &collection: m_collections) {
collection.levels.sort();
std::sort(collection.levels.begin(), collection.levels.end());
}
}

@@ -20,19 +20,6 @@
#include <cstdio>
#include <sstream>
#include <vector>
#include <stdlib.h>

template <typename T>
class SortableVector : public std::vector<T> {
public:
SortableVector() : std::vector<T>() {}

void sort()
{
qsort(std::vector<T>::data(), std::vector<T>::size(), sizeof(T),
(int (*)(const void *, const void *))T::compare);
}
};

struct LevelDesc {
LevelDesc()
@@ -45,7 +32,7 @@ struct LevelDesc {
{
}

static int compare(const LevelDesc *a, const LevelDesc *b);
void swap(LevelDesc &a, LevelDesc &b);

std::string file;
};
@@ -65,11 +52,11 @@ struct Collection {
{
}

static int compare(const Collection *a, const Collection *b);
void swap(Collection &a, Collection &b);

std::string file;
std::string name;
SortableVector<LevelDesc> levels;
std::vector<LevelDesc> levels;
};

class Levels
@@ -107,7 +94,7 @@ class Levels
bool scanCollection(const std::string& file);

int m_numLevels;
SortableVector<Collection> m_collections;
std::vector<Collection> m_collections;
};

#endif //LEVELS_H

0 comments on commit e9bd8b5

Please sign in to comment.
You can’t perform that action at this time.