Merge pull request #484 from Wargus/proj

Improve `ranges::find` to support projection.
This commit is contained in:
Joris Dauphin 2023-09-04 13:19:33 +02:00 committed by GitHub
commit 372b292930
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 18 additions and 8 deletions

View file

@ -165,6 +165,17 @@ fs::path GetExecutablePath();
/*----------------------------------------------------------------------------
-- Ranges
----------------------------------------------------------------------------*/
#include <functional>
struct identity
{
template <typename T>
T &&operator()(T &&arg) const
{
return std::forward<T>(arg);
}
};
namespace ranges
{
@ -180,10 +191,11 @@ namespace ranges
std::iota(begin(range), end(range), startValue);
}
template<typename Range, typename Value>
auto find(Range& range, const Value& value)
template<typename Range, typename Value, typename Proj = identity>
auto find(Range& range, const Value& value, Proj proj = {})
{
return std::find(begin(range), end(range), value);
return std::find_if(
begin(range), end(range), [&](const auto &elem) { return std::invoke(proj, elem) == value; });
}
template <typename Range, typename Predicate>

View file

@ -307,8 +307,7 @@ static int CclDefineSpell(lua_State *l)
const int args = lua_gettop(l);
std::string_view identname = LuaToString(l, 1);
const auto it = ranges::find_if(SpellTypeTable,
[&](const SpellType *spell) { return spell->Ident == identname; });
const auto it = ranges::find(SpellTypeTable, identname, &SpellType::Ident);
SpellType *spell = nullptr;
if (it != SpellTypeTable.end()) {
spell = *it;

View file

@ -416,7 +416,7 @@ void InitSpells()
*/
SpellType &SpellTypeByIdent(const std::string_view &ident)
{
auto it = ranges::find_if(SpellTypeTable, [&](const SpellType* spell) { return spell->Ident == ident; });
auto it = ranges::find(SpellTypeTable, ident, &SpellType::Ident);
if (it != SpellTypeTable.end()) {
return **it;
}

View file

@ -188,8 +188,7 @@ CUserInterface::CUserInterface() :
*/
CPopup &PopupByIdent(std::string_view ident)
{
const auto it =
ranges::find_if(UI.ButtonPopups, [&](CPopup *popup) { return popup->Ident == ident; });
const auto it = ranges::find(UI.ButtonPopups, ident, &CPopup::Ident);
if (it != UI.ButtonPopups.end()) {
return **it;
}