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

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.


graph_t


graph_t (,, Iterable,);



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.


int weights


weight


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?


weight




1 Answer
1


#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));



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.