1

std::map別のイテレータのイテレータをstd::mapキータイプとして使用するを作成したいVisualStudio2008 C++03アプリケーションがあります。しかし、キータイプを使用してそのマップから要素を消去しようとすると、問題が発生します。

この例では、の要素MyListが5分以上経過すると、タイマーが起動してマップから要素を削除し、そのエージングタイマーを破棄する必要があります。

typedef std::map< Foo, FooBar > MyList;
typedef std::map< MyList::iterator, boost::shared_ptr< Timer > > MyListAgeTimers;

class A
{
public:

    void AddItem( Foo& f, FooBar& fb )
    {
        CriticalSection::Guard g( lock_ );
        std::pair< MyList::iterator, bool > new_foo = 
            my_list_.insert( std::make_pair( f, fb ) );
        if( new_foo.second )
        {
            timers_.insert( std::make_pair( 
                new_foo.first, 
                boost::make_shared< Timer >( FiveMinutes, boost::bind( &A::OnAgeTimer, this, new_foo.first ) ) ) );
        }
    };

    void OnAgeTimer( MyList::iterator item )
    {
        CriticalSection::Guard g( lock_ );

        // erase by key-type generates an error:
        // functional(143) : error C2676: binary '<' : 'const std::_Tree<_Traits>::iterator' does not define this operator or a conversion to a type acceptable to the predefined operator
        timers_.erase( item );

        // erase by iterator. works okay.
        my_list_.erase( item );
    };

private:
    MyList my_list_;
    MyListAgeTimers timers_;
    CriticalSection lock_;
};

あるマップから別のマップへのキータイプとしてイテレータを使用できませんか?または、これに特化したものを定義する必要がありますoperator<か?

編集:

(私にとって)明らかなことはこれだけです:

namespace std {
inline bool operator <( const MyList::iterator& a, const MyList::iterator& b )
{
    return a->first < b->first;
}
};

std::operator<しかし、それが正しければ、 2つのイテレータを比較するときのデフォルトの動作ではないのはなぜですか?

4

1 に答える 1

6

std::map<key, value>keyが必要operator<です; これは、マップオブジェクトが一致するキーを見つけるために使用するものです。双方向イテレータですstd::map<x, y>::iterator。がないため、2つのイテレータを比較し、どちらが優先されるかを決定するための独自のオブジェクトまたは関数オブジェクトを提供しない限り、別のマップのキータイプとして使用することはできません。operator<operator<

于 2012-10-08T15:49:37.027 に答える