it2是顺序迭代器,rit是逆序迭代器,想通过逆序迭代器删除某一值,逆序迭代器需要用到base()转为顺序迭代器删除,但是直接转后删除发现逆序判断5,结果删了6,发现base()后会错一位,用以下方式移位,为何方法二失败了
方法1:成功
it2 = (++rit).base();
rit++
testearse.erase(it2->first);
方法2:失败
it2 = rit.base();
it2--;
rit++;
testearse.erase(it2->first);
#include <math.h>
#include <iostream>
#include<string>
#include "map"
using namespace std;
struct CmpByKeyBig {
bool operator()(const int& k1, const int& k2)const {
return k1 < k2;
}
};
int main() {
map<double, int, CmpByKeyBig> testearse;
for (int i = 11; i >0; i--){
testearse[double(i)] = i;
//testearse.insert(make_pair(i, i));
}
map<double, int>::reverse_iterator ritaa = testearse.rend();
map<double, int>::iterator it2;
while (rit != testearse.rend())
{
if ( rit->second == 5.0){
it2 = (++rit).base();
printf("it2->firt=%f,it2->second%d\n", it2->first,it2->second);
rit++;
testearse.erase(it2->first);
continue;
}
rit++;
}
return 0;
如果将while循环改为以下方式就无法运行
{
if ( rit->second == 4.0){
it2 = rit.base();
printf("it2->firt=%f,it2->second%d\n", it2->first,it2->second);
rit++;
it2--;
testearse.erase(it2->first);
continue;
}
rit++;
}