Home > Enterprise >  How to compare two map iterator in c ?
How to compare two map iterator in c ?

Time:11-26

#include <iostream>
#include<vector>
#include<map>
using namespace std;
int main() {
   vector<int> v1{1,2,3,4,5};
    auto it1 = v1.begin();
    auto it2 = v1.end();
    if(it1<it2){
        cout<<"TRUE"<<endl;             // Output: TRUE
    }

    map<int,int> m;
    m.insert(make_pair(1,2));
    m.insert(make_pair(5,7));
    auto it3 = m.begin();
    auto it4 = m.end();
    if(it3<it4){
        cout<<"TRUE"<<endl;           
    }   
    /*
    error: no match for 'operator<' (operand types are 'std::_Rb_tree_iterator<std::pair<const int, int> >' and 'std::_Rb_tree_iterator<std::pair<const int, int> >')
   18 |     if(it3<it4){
      |        ~~~^~~~
    */

}

Line (it1<it2) works fine when using vector but (it3<it4) does not work when using map? Please explain this concept.

CodePudding user response:

Line (it1<it2) works fine when using vector but (it3<it4)

Vector iterators are random access iterators. Random access iterators can be compared for order.

but (it3<it4) does not work when using map?

Map iterators are not random access iterators. They cannot be compared for order.

However, if you know the comparator of the map, then you can indirect through both iterators, and compare the keys with the comparator. You must check for end iterator first since you cannot get a key from it (but you do know that it's after all other iterators). This only works with ordered maps such as std::map. It does not work with hashmaps such as std::unordered_map. It also won't find out the relative order of two iterators to identical elements in a multi map.

In general, given a pair of forward iterators and the end iterator, you can find out the pair of iterators by doing linear search starting from one iterator, until you find either second iterator or the end of the container. If you find end before the other iterator, then other is first; If you do find the other iterator then it's after. This of course has linear worst case complexity.

CodePudding user response:

See here for an overview of iterator categories: https://en.cppreference.com/w/cpp/iterator.

std::map has bidirectional iterators while std::vector has randomaccess iterators. The latter can be comapred via <, the first not.

If you want to know which element comes first in the map, you can use the fact that a std::maps elements are sorted with respect to keys:

if (it3->first < it4->first) { ...

In general you need to take into account that the map might use a custom comparator, hence the more generic way would be

if ( m.key_comp()(it3->first,it4->first) ) { ...

However, either way will fail when one of the iterators equals the end of the map, because you cannot dereference it to get a key.

  • Related