I wrote a timetabling program and I have been using a matrix to check for clashes between courses. Index (i, j) in the matrix tells us how many people are in both courses i and j.
My previous Matrix was just using nested vectors:
std::vector<std::vector<int>> clashes;
This would throw std::bad_alloc because the matrix is of dimension 18000 x 18000.
Since many of the entries would be 0, I made my own matrix class using unordered maps. This preserves a lot of data as it uses a default value for all of entries that have not been given a value.
template <typename T>
class UMapMatrix
{
public:
UMapMatrix(T default_val) : default_val(default_val) {
}
T get(const int& a, const int& b) const {
int x, y;
if (a < b) {
x = a;
y = b;
}
else {
x = b;
y = a;
}
auto search = data.find(x);
if (search != data.end()) {
auto search2 = search->second.find(y);
if (search2 != search->second.end()) {
return search2->second;
}
}
return default_val;
}
void set(const int& a, const int& b, T val) {
if (a < b) data[a][b] = val;
else data[b][a] = val;
}
private:
T default_val;
std::unordered_map<int, std::unordered_map<int, T>> data;
};
Are there any significant improvements that could be made to the memory usage and/or speed? Are there any other data structures that could be used here?