Home > Back-end >  How to understand how iterator and .end() work in c ?
How to understand how iterator and .end() work in c ?

Time:06-28

I'm learning c newly, and can't figure out the iterator... for instance, I have the code below with a map and, despite research, can't figure out the .end(), iterator it as well as first

   std::map<int, double> e;
    e[1] = 10.0;
    e[2] = 20.0;
    e[3] = 30.0;
    e[4] = 40.0;
    map<int, double>::iterator it;
    
    it = e.end();
    it--;
    int d = 1.0*it->first / 50000;

Could someone indicates me the meaning of each step of this code, from the map initialization to the last line ! Thanks !

CodePudding user response:

For simplicity, you can imagine a map using this visualization

[X,X,X,X,X,X,X]_
 A             B

map.begin() will return a pointer to point A

map.end() will return a pointer to point B

An element in a map is a pair of (key, value). Thus, first refers to the key.

All elements in a map is sorted based on the key. Thus, your code is trying to get the maximum key divided by 50000

CodePudding user response:

Iterators are used to point at the memory addresses of STL containers.

.begin() points to the first element of container address.

.end() points to the last element of container address 1.

this link explain iterator : iterator

  • Related