Search code examples
c++iteratormember

How to get iterator over only the members of a class inside a container in C++


In C ++, I wonder if there is a way to get an iterator that only traverses a specific member of a class when it is contained in a container.
The situation is as follows.

class Edge : public std::pair<int, int> {
private:
    int length;
public:
    int weight;
    Edge::Edge(int v1, int v2): std::pair<int, int>(v1, v2) { }
}

int main() {
    enum nodes { A, B, C, D, E };
    const int num_nodes = 5;
    vector<Edge> edge_vec = { Edge(A, C), Edge(C, D), Edge(B, D), Edge(B, E) };
    int weights[] = { 1, 2, 7, 3 };  // I don't like this part.
    graph_t g(edge_vec.begin(), edge_vec.end(), weights, num_nodes);
}

The definition of graph_t is graph_t (,, Iterable,);.
Therefore, any Iterable can be assigned as the third argument.

The problem is this.
I do not want to use a separate int weights[] array because Edge class already have weight.
So I want to get an Iterator that can be initialized as follows and then traversed.

edge_vec[0].weight = 1;
edge_vec[1].weight = 2;
edge_vec[2].weight = 7;
edge_vec[3].weight = 3;

In this case, weight is updated frequently, so I want to access it with a pointer instead of a copy in a separate data structure.
What is the most effective and elegant way to handle this?


Solution

  • #include <boost/iterator/transform_iterator.hpp>
    // ...
    boost::transform_iterator wbegin(edge_vec.begin(), std::mem_fn(&Edge::weight));
    boost::transform_iterator wend(edge_vec.end(), std::mem_fn(&Edge::weight));