2012-09-19 29 views
7

我有这段代码,我无法理解部分equal_range方法返回迭代器。 我知道的范围是与内部的两个多重映射对象的对象,但我不明白,这就是为什么有'for (it = range.first; it != range.second; ++it)' - 这是什么意思是什么呢?C++:STL multimap.equal_range()

// multmap.cpp -- use a multimap 
#include <iostream> 
#include <string> 
#include <map> 
#include <algorithm> 

typedef int KeyType; 
typedef std::pair<const KeyType, std::string> Pair; 
typedef std::multimap<KeyType, std::string> MapCode; 

int main() 
{ 
using namespace std; 
MapCode codes; 
codes.insert(Pair(415, "San Francisco")); 
codes.insert(Pair(510, "Oakland")); 
codes.insert(Pair(718, "Brooklyn")); 
codes.insert(Pair(718, "Staten Island")); 
    codes.insert(Pair(415, "San Rafael")); 
    codes.insert(Pair(510, "Berkeley")); 

    cout << "Number of cities with area code 415: " 
    << codes.count(415) << endl; 
    cout << "Number of cities with area code 718: " 
    << codes.count(718) << endl; 
    cout << "Number of cities with area code 510: " 
    << codes.count(510) << endl; 
    cout << "Area Code City\n"; 

    MapCode::iterator it; 
    for (it = codes.begin(); it != codes.end(); ++it) 
    cout << " " << (*it).first << " " 
    << (*it).second << endl; 

    pair<MapCode::iterator, MapCode::iterator> range 
     = codes.equal_range(718); 

    cout << "Cities with area code 718:\n"; 
    for (it = range.first; it != range.second; ++it) //<------------------ here 
    cout << (*it).second << endl; 
    return 0; 
} 

回答

11

对中的迭代器定义的项目等于搜寻内容的方式[range.first, range.second)键范围。

这意味着,在该范围迭代,你range.first启动和推进迭代,直到它到达range.second,这意味着你刚刚走下同等范围。从概念上说,它与迭代范围[container.begin(), container.end())时发生的情况相同。

+0

我认为你的回答是最理解我,因为它混淆了,看在迭代对象对成员。但是,如果它与* [container.begin(),container.end())'相同*没关系。谢谢 – ashur

4

equal_range返回一对迭代器i1, i2,使得范围[i1, i2)内的所有元素具有相同的密钥。因此,为了遍历代码为718的所有城市,请致电equal_range,然后从返回的对first到返回的对second进行迭代。

+0

简短而甜美 – ammassalik

24

equal_range的结果,即您的range对象,是两个迭代器[beginning-of-range, end-of-range)。所以,你要遍历[range.first, range.second)

auto range = m.equal_range(4); 

+---+---+---+---+---+---+---+---+---+ 
| 2 | 3 | 3 | 4 | 4 | 4 | 4 | 5 | 6 | =: m 
+---+---+---+---+---+---+---+---+---+ 
      ^   ^
      |    | 
     range.first range.second