Skip to content

Instantly share code, notes, and snippets.

@ardabbour
Created September 20, 2020 15:03
Show Gist options
  • Save ardabbour/79df81c30d675071a84e48ae81414495 to your computer and use it in GitHub Desktop.
Save ardabbour/79df81c30d675071a84e48ae81414495 to your computer and use it in GitHub Desktop.
#include <algorithm>
#include <stdexcept>
#include <vector>
/**
* @brief Find the best vector of costs arranged in descending order from a vector of vectors of costs.
*
* @tparam T A comparable type.
* @param costs A vector of vectors of prioritized costs.
* @param minimize Whether or not smaller values are better.
* @return The best vector.
*/
template <typename T>
const std::vector<T> multi_lex(const std::vector<std::vector<T>>& costs, const bool& minimize) {
if (costs.empty()) {
throw std::length_error("There are no costs to compare!");
}
const unsigned int size = costs.at(0).size();
for (const auto& i : costs) {
if (i.size() != size) {
throw std::length_error("Cost sizes don't match!");
}
}
const auto comp = [minimize](T a, T b) { return minimize ? a < b : b < a; };
std::vector<T> best{costs.at(0)};
for (const auto& i : costs) {
if (std::lexicographical_compare(best.begin(), best.end(), i.begin(), i.end(), comp)) best = i;
}
return best;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment