mercredi 28 octobre 2020

Assigning a const_iterator to an iterator

I have the below snippet of code (which you can run here: http://coliru.stacked-crooked.com/a/2f62134b5c125051)

#include <iostream>
#include <set>
#include <map>

int main() 
{
    std::set<std::pair<const int, const int>> const mySet0; // value_type = std::pair<const int, const int>
    for (std::set<std::pair<const int, const int>>::iterator it  = mySet.cbegin(); it != mySet.cend(); ++it)
    {
        std::cout<<"set it = " << it->first << " " << it->second << std::endl;
    }

    std::map<const int, const int> const myMap0; // value_type = std::pair<const int, const int>
    for (std::map<const int, const int>::iterator it  = myMap.cbegin(); it != myMap.cend(); ++it)
    {
        std::cout<<"map it = " << it->first << " " << it->second << std::endl;
    }   
}

Can someone please explain me why for std::set the below does not throw any error:

std::set<std::pair<const int, const int>>::iterator it  = mySet.cbegin();

while for std::map the below throws error (no known conversion from _Rb_tree_const_iterator<std::pair<const int, const int> > to _Rb_tree_iterator<std::pair<const int, const int> >) as expected:

std::map<const int, const int>::iterator it  = myMap.cbegin();

How does it work for std::set? Shouldn't assigning a const_iterator to an iterator always throw an error?

Aucun commentaire:

Enregistrer un commentaire