2011-06-28 29 views
1

我有地图。我需要从一开始就迭代它,而不是从期望的关键。 我试过了;我可以从期望的密钥迭代地图吗?

int candidate_s; 
    map<int, vector<int> >::iterator map; 
    for(map = a_list.begin()+candidate_s; map! = a_list.end(); map++){ 
     cout<<map->first<<"= "; 
     for(vector<int>::iterator vec=map->second.begin(); vec!=map->second.end(); vec++){ 
      cout<<*vec<<" ";    
     } 
    cout<<endl; 
    } 

,我得到了以下错误消息:

D:\c_mess\merging\src\main.cpp no match for 'operator+' in '(+a_list)->std::map<_Key, _Tp, _Compare, _Alloc>::begin [with _Key = int, _Tp = std::vector<int, std::allocator<int> >, _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, std::vector<int, std::allocator<int> > > >]() + candidate_s' 

请帮我纠正。

+1

的std ::地图没有随机访问迭代器,你不能将号码添加到迭代器。 'candidate_s'应该是什么?此外,请格式化代码,使其更具可读性(带空格)。 –

+0

@ Kerrek >>对不可读性感到抱歉。 candidate_s是一个整数值。我也可以说,这是我想要的地图的关键。 (不是从开始) – niro

+0

@Giro:很难想象你能如何有效地得到这个整数,并且几乎可以肯定有更好的方法来获得迭代器。尽管如此,您可以使用'std :: advance(it,n);'来推进迭代器。 –

回答

2

在假设candidate_s是的std::map的键的类型:

std::map<int, vector<int> >::const_iterator startIt = a_list.find(candidate_s); 
for(; startIt != a_list.end(); ++startIt) { 
    //Do stuff 
} 
+0

你可以把它卷成一条线...... –

+0

@尼科尔,非常感谢。 – niro

3

您可以使用map::find来获取指定键的迭代器。

如果candidate_s应该是一个索引,为什么不使用presized向量呢?那么你将有更快的查找时间。但是,如果您的整数键稀疏/具有宽范围的值,则基于矢量的解决方案可能不适用。

+1

链接是'std :: find'。 –

+0

@Steve Jessop:对不起,我对此表示感谢。 – GWW

相关问题