member iterator - request for comment
Hi,
Recently I've met the need to perform operations like this quite
often:
struct A {
int val;
}
....
std::vector<A> as;
....
std::set<int> vals;
std::vector<A>::const_iterator it, end = as.end();
for (it = as.begin(); it != end; ++it) {
vals.insert(it->val);
}
that is, to perform some action on one of the members of each of the
collection's elements. I couldn't find any solutions within the STL,
so I've created my own MemberIterator class. The code is:
template<class Iterator, class PointerToMember, class Member>
class MemberIterator : public Iterator {
public:
MemberIterator(Iterator it, PointerToMember ptr) : Iterator(it),
ptr_(ptr) {
}
Member& operator*() {
return Iterator::operator*().*ptr_;
}
private:
PointerToMember ptr_;
};
template<class Member, class Iterator, class PointerToMember>
MemberIterator<Iterator, PointerToMember, Member> makeMemberIterator(
Iterator it, PointerToMember ptr) {
return MemberIterator<Iterator, PointerToMember, Member>(it, ptr);
}
Given this solution, I can write:
std::copy(makeMemberIterator<int>(as.begin(), &A::val),
makeMemberIterator<int>(as.end(), &A::val), std::back_inserter(vals));
and it works just fine.
I would like to know your opinion on
1. whether this class is implemented correctly or how I could make it
better
2. whether I should attempt to write stuff like this or use some STL
provided solution that I'm not aware of
Thanks,
Mikolaj
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]