gpt4 book ai didi

c++ - 使用一个映射中的迭代器作为另一个映射的键类型

转载 作者:行者123 更新时间:2023-11-30 00:55:12 25 4
gpt4 key购买 nike

我有一个 Visual Studio 2008 C++03 应用程序,我想在其中创建一个 std::map使用来自另一个 std::map 的迭代器作为它的键类型。但是,当我尝试使用键类型从该映射中删除元素时遇到了问题。

在此示例中,当 MyList 中的元素超过 5 分钟,计时器应该触发并将其从 map 中删除并销毁其年龄计时器。

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< 的默认行为?比较两个迭代器时?

最佳答案

std::map<key, value>要求 key有一个operator< ;这就是 map 对象用来查找匹配键的方法。 std::map<x, y>::iterator是一个双向迭代器;它没有 operator< ,因此除非您提供自己的 operator<,否则您不能将其用作另一个 map 中的键类型或一个函数对象来比较两个迭代器并决定哪个迭代器先于另一个。

关于c++ - 使用一个映射中的迭代器作为另一个映射的键类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12784860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com