繁体   English   中英

std :: map迭代器自身

[英]std::map of iterators to itself

我的目标是将一种类型的元素映射到同一类型的其他元素。 为了简单起见,假设它们为size_t

std::map<size_t, size_t> myMapping;

这样就可以了,但是如果我想跟随一堆这样的链接(它们都是相同的地图),则每个步骤都是一个log(n)查找。

size_t k = /*whatever*/;
myMapping[myMapping[myMapping[k]]];   //3 * log(n)

我想利用以下事实:映射迭代器保持有效,并且具有将size_t映射到迭代器本身的映射。

typedef /*myMapTemplate*/::iterator map_iter;
std::map<size_t, map_iter> myMapping;

size_t k = /*whatever*/
map_iter entryPoint = myMapping.find(k);
entryPoint->second->second->first;   //log(n) + 2 constant time operations

我将如何写这种类型? 我知道复制将使迭代器保留在旧地图上,并计划自己进行处理。

我了解您要映射的问题: key->map<key,>::iterator

因此,这里是一个以map迭代器作为值的结构:

template <
    template <class K, class V, class C, class A> class mapImpl, 
   class K, 
   class V, 
   class C=std::less<K>, 
   class A=std::allocator<std::pair<const K, V> >
>
class value_with_iterator {
public:
   typedef typename mapImpl<const K,value_with_iterator,C,A>::iterator value_type;
   value_type value;
};

使用上述结构定义的地图:

typedef std::map<size_t, value_with_iterator <std::map, size_t, size_t> > map_size_t_to_itself;

一些插入方法-链接密钥本身:

map_size_t_to_itself::iterator insert(map_size_t_to_itself& mapRef, size_t value)
{
   map_size_t_to_itself::value_type v(value, map_size_t_to_itself::mapped_type());
   std::pair<map_size_t_to_itself::iterator, bool> res = mapRef.insert(v);
   if (res.second) 
     res.first->second.value = res.first;
   return res.first;
}

和简单的测试:

int main() {
   map_size_t_to_itself mapObj;
   map_size_t_to_itself::iterator i1 = insert(mapObj, 1);
   map_size_t_to_itself::iterator i2 = insert(mapObj, 1);
   map_size_t_to_itself::iterator i3 = insert(mapObj, 2);

   std::cout << i1->first << ": " << i1->second.value->first << std::endl;
   std::cout << i2->first << ": " << i2->second.value->first << std::endl;
   std::cout << i3->first << ": " << i3->second.value->first << std::endl;
}

使用OUTPUT:

1: 1
1: 1
2: 2

完整链接: http : //ideone.com/gnEhw

如果我正确理解了您的问题,我想我会将元素保留在向量中,并使用索引向量进入第一个向量,以实现所需的间接寻址。 如果还需要有序访问,则可以始终将第一个向量的元素放入地图中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM