Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming first and second of a map iterator

Tags:

Is there any way to rename the first and second accessor functions of a map iterator. I understand they have these names because of the underlying pair which represents the key and value, but I'd like the iterators to be a little more readable. I think this might be possible using an iterator adaptor, but I'm not sure how to implement it.

Please note that I can't use boost.

Example of what I mean:

map<Vertex, Edge> adjacency_list; for(map<Vertex, Edge>::iterator it = adjacency_list.begin();     it != adjacency_list.end();     ++it) {     Vertex v = it->first;     //instead I would like to have it->vertex } 
like image 618
user281655 Avatar asked Sep 30 '09 19:09

user281655


People also ask

Can key of map be changed?

The replace(K key, V value) method of Map interface, implemented by HashMap class is used to replace the value of the specified key only if the key is previously mapped with some value.

What is iterator second?

Refers to the first ( const ) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression: i->second.

Does MAP return an iterator?

map() loops over the items of an input iterable (or iterables) and returns an iterator that results from applying a transformation function to every item in the original input iterable.


1 Answers

If you're just concerned about readability you could do something like this:

typedef map<Vertex, Edge> AdjacencyList; struct adjacency {     adjacency(AdjacencyList::iterator& it)        : vertex(it->first), edge(it->second) {}     Vertex& vertex;     Edge& edge; }; 

And then:

Vertex v = adjacency(it).vertex; 
like image 171
Georg Fritzsche Avatar answered Sep 27 '22 18:09

Georg Fritzsche