0

我需要知道两个指向 STL 映射的指针之间的区别

例如:使用矢量很简单

vector<pair<int, int> > v;
v.push_back(make_pair(0, 1));
v.push_back(make_pair(2, 3));
v.push_back(make_pair(4, 5));
v.push_back(make_pair(6, 7));
v.push_back(make_pair(8, 9));

vector<pair<int, int> >::iterator itrBegin = v.begin();
vector<pair<int, int> >::iterator itrEnd = v.end();

cout << itrEnd - itrBegin << endl;

输出5

但是,我想使用 STL map 执行相同的操作

map<int, int> m;
m[0] = 1;
m[2] = 3;
m[4] = 5;
m[6] = 7;
m[8] = 9;

map<int, int>::iterator itrB = m.begin();
map<int, int>::iterator itrE = m.end();

cout << ????????????? << endl;
4

2 回答 2

6

您可以使用std::distance

std::cout << std::distance(iterB, iterE) << std::endl;
于 2013-10-16T22:43:20.400 回答
2

关联容器(List、set、multiset、map、multimap)迭代器是双向迭代器,而对于序列容器(vector、deque),它们的迭代器是随机访问迭代器

双向迭代器,仅定义了以下运算符。

Expression    Effect
--iter        Steps backward (returns new position)
iter--        Steps backward (returns old position)

这意味着您不能调用Bidirectional iterator m.end() - m.begin()

随机访问迭代器定义了以下运算符。

Expression      Effect
iter[n]         Provides access to the element that has index n
iter+=n         Steps n elements forward (or backward, if n is negative)
iter-=n         Steps n elements backward (or forward, if n is negative)
iter+n          Returns the iterator of the nth next element
n+iter          Returns the iterator of the nth next element
iter-n          Returns the iterator of the nth previous element
iter1-iter2     Returns the distance between iter1 and iter2
iter1<iter2     Returns whether iter1 is before iter2
iter1>iter2     Returns whether iter1 is after iter2
iter1<=iter2    Returns whether iter1 is not after iter2
iter1>=iter2    Returns whether iter1 is not before iter2

所以使用std::distance,只要迭代器是InputIterator就可以工作

于 2013-10-16T23:02:35.083 回答