Is there an iterator, perhaps in the standard library, akin to back_inserter
in the sense of calling a function on being dereferenced, that when dereferenced, returns not the item it's pointing to but an attribute of it?
I want to take an iterator to the start and end of a container (e.g. a vector) of custom-defined structs and I want the iterator on being dereferenced to access a specific member of that struct and to work on that directly. Perhaps I can just define that behaviour by having it invoke a lambda of some sort on that element that can then return the desired member field.
Reason being is I don't want to maintain a separate container of those member fields.
Something like this:
struct Person
{
std::string m_Name;
std::uint64_t m_Age;
};
int main()
{
std::vector<Person> people { Person("a", 15), Person("b", 25), Person("c", 40) };
// MagicIterator is what I'm after
auto ageIter = MagicIterator(people, [](const Person &person) { return person.m_Age; });
// sample use case, foo here expects a container of arithmetic types
auto out = foo<std::uint64_t>(ageIter.begin(), ageIter.end());
return 0;
}
Right now, I think I'd first have to extract out all the ages in a separate container and then pass that new container to foo
which I want to avoid.
I'm happy with anything up to and including C++17, Boost is okay too.