开发者

Can I iterate a map from a desired key?

I have map. I need to iterate it not from the beginning, but from the desired key. I tried it as;

  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;
  }

and I got the following error message:

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' 

Please help me to rectify 开发者_如何学Gothis.


You can use map::find to get an iterator to a specific key.

If candidate_s is supposed to be an index why not use a presized vector instead? You would have faster look-up times then. However, the vector based solution may not be applicable if your integer keys are sparse / have a wide range of values.


On the assumption that candidate_s is of the type of the std::map's key:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜