-> first / second for an empty map iterator to start


I can not understand what is happening in this fragment.
The map link says: "If the container is empty, the return value of the iterator should not be dereferenced."
But what about some_map->begin()->second? on a blank card.
I thought this would be invalid, but this code prints "0". Can anyone explain why?

int main()
{
 map<int,int> a;

 printf("%d",a.begin()->second);
 return 1;
}

Thank!

+4
source share
3 answers

From this std::map::beginlink

If the container is empty, the returned iterator will be equal end()

Then look at this linkstd::map::end :

; undefined.

[ ]

, undefined , , . .

+5

. , ->second undefined , .

- undefined, .

+1

, undefined, 0 undefined - .

, , , , segfault. , map . node .

, map node (, node ). . , operator --() eg. , - , , , , node ( , ):

template<typename U, typename V>
typename map<U,V>::iterator &map<U,V>::iterator::operator --()
{
    if ( node_ != nullptr )
    {
        // go to predecessor
        if ( node_->leftChild_ != nullptr )
        {
            for ( node_ = node_->leftChild_; node_->rightChild_ != nullptr; node_ = node_->rightChild_ );
        }
        else
        {
            node *n;
            do
            {
                n = node_;
                node_ = node->parent_;
                // may not go before begin()
                assert( node_ != nullptr );
            } while ( n == node_->leftChild_ );
        }
    }
    else
    {
        // point to last node - map must not be empty
        assert( container_->root_ != nullptr );
        for ( node_ = container_->root_; node_->rightChild_ != nullptr; node = node->rightChild_ );
    }
    return *this;
}

, node, node node, , , . container_ , iterator, . ( , ++ 11 " " , , . . MINOR UPDATE: , .)

, end() "" . , operator *() :

template<typename U, typename V>
typename map<U,V>::reference map<U,V>::iterator::operator *() const
{
    // cannot dereference end iterator
    assert( hasSuccessor(node_) );
    return *node_;
}

, . hasSuccessor? , , , node_ . , .. . - O (1), O (log N), Θ (1) . , , , , , " " - node. , . , node, "" , . , "" , , segfault, , .

, , , , -135, - "" 8-9- . map , , . operator [], , . , :

  • , - , int, map, , int{}, . new.
  • memset node . , .
  • , , "" , . , , , , . , memset , .
0

Source: https://habr.com/ru/post/1693245/


All Articles