Fil*_*ipp 10 c++ dictionary iterator stl std
我的目标是将类型的元素映射到相同类型的其他元素.假设它们是size_t为了简单起见.
std::map<size_t, size_t> myMapping;
Run Code Online (Sandbox Code Playgroud)
这样做,但如果我想跟随一堆这样的链接(它们都是相同的地图),每一步都是log(n)查找.
size_t k = /*whatever*/;
myMapping[myMapping[myMapping[k]]]; //3 * log(n)
Run Code Online (Sandbox Code Playgroud)
我想利用map迭代器保持有效的事实,并有一个映射将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
Run Code Online (Sandbox Code Playgroud)
我该怎么写这种类型?我知道复制会将迭代器保留在旧地图上并计划自己处理.
我理解您想要地图的问题: 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;
};
Run Code Online (Sandbox Code Playgroud)
使用上面的struct定义的地图:
typedef std::map<size_t, value_with_iterator <std::map, size_t, size_t> > map_size_t_to_itself;
Run Code Online (Sandbox Code Playgroud)
一些插入方法 - 将键与自身链接:
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;
}
Run Code Online (Sandbox Code Playgroud)
而且简单的测试:
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;
}
Run Code Online (Sandbox Code Playgroud)
与OUTPUT:
1: 1
1: 1
2: 2
Run Code Online (Sandbox Code Playgroud)
完整链接:http://ideone.com/gnEhw