Code: Select all
struct Data {
int value;
int DataId;
};
< /code>
Ich habe eine Sammlung dieser Daten, aus denen ich häufig ein Element basieren und seinen Wert ändern muss (aber nicht der ID).class Comparator {
/// dummy type for declaring is_transparent type
struct SIsTransparentTag;
public:
// tag (falsely) indicating that operator() is transparent, i.e. accepts
// any type of argument: this is a workaround to allow std::set::find to
// use a int key instead of a full Data object.
// https://en.cppreference.com/w/cpp/container/set/find
// https://www.fluentcpp.com/2017/06/09/search-set-another-type-key/
using is_transparent = SIsTransparentTag;
// comparator between two Data
bool operator()(const Data &lhs, const Data &rhs) const {
return lhs.DataId < rhs.DataId;
}
// comparator between a Data and an id
bool operator()(const Data &lhs, const int id) const {
return lhs.DataId < id;
}
// comparator between an id and a Data
bool operator()(const int id, const Data &rhs) const {
return id < rhs.DataId;
}
};
< /code>
Dann habe ich einen Leseschreiber-Getter geschrieben: < /p>
Data* GetRWDataFromID(std::set &collection,int id)
{
auto it = collection.find(id);
if (it == std::end(collection))
{
return nullptr;
}
// UB as soon as I will modify Data!!!
return const_cast(&(*it));
}
< /code>
Spielplatz < /p>
std::set::find()