13

我有这段代码,但我无法理解equal_range方法返回迭代器的部分。我知道范围是对象,里面有两个多图对象,但我不明白,为什么会有 'for (it = range.first; it != range.second; ++it)'- 这到底是什么意思?

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

3 回答 3

30

的结果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
于 2012-09-19T13:04:23.127 回答
12

该对中的迭代器定义项的范围,其键等于您在该方式中搜索的内容[range.first, range.second)

这意味着要在该范围上进行迭代,您从range.first迭代器开始并前进,直到它到达range.second,这意味着您刚刚离开了相等的范围。从概念上讲,它与迭代 range 时发生的情况相同[container.begin(), container.end())

于 2012-09-19T13:03:29.087 回答
4

equal_range返回一对迭代器i1, i2,使得范围内的所有元素[i1, i2)都具有相同的键。因此,为了遍历代码为 718 的所有城市,您调用equal_range,然后从返回的对迭代到first返回的对second

于 2012-09-19T13:03:58.963 回答