0

STLマップへの2つのポインターの違いを知る必要があります

例: vector の使用は簡単です

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

連想コンテナー (リスト、セット、マルチセット、マップ、マルチマップ) 反復子は双方向反復子であり、シーケンス コンテナー (ベクター、デキュー) の反復子はランダムアクセス反復子です。

双方向 iterator、以下の演算子のみが定義されています。

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 に答える