神秘的集合迭代器行为

Mysterious set iterator behavior

如果我用“4 petr egor”的输入编译并运行下面的程序,我得到的输出是“2 2 2”,但预期的输出应该是“2 1 2”,因为在倒数第二个 if 语句中,如果我输出 *iter,我得到“2”,如果我输出 *charMap.begin()->second.begin(),我得到“1”。为什么会这样?

#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <algorithm>

using namespace std;

int hammingdist(const string& S, const string& T) {
    int count = 0;
    for (int i = 0; i < S.size(); ++i) {
        if (S[i] != T[i]) count++;
    }
    return count;
}

int main() {
int n;
string T, S;
cin >> n >> T >> S;

map<char, set<int>> charMap;
vector<int> diffVec;

for (int i = 0; i < S.size(); ++i) {
    if (T[i] != S[i]) diffVec.push_back(i);
}

for (int i = 0; i < diffVec.size(); ++i) {
    charMap[S[diffVec[i]]].insert(diffVec[i]);
    charMap[T[diffVec[i]]].insert(diffVec[i]);
}

auto removeIter = charMap.begin();
while (removeIter != charMap.end()) {
    if (removeIter->second.size() == 1) {
        auto toRemove = removeIter;
        ++removeIter;
        charMap.erase(toRemove);
        continue;
    }
    if (removeIter != charMap.end())
        ++removeIter;
}

if (charMap.empty()) {
    cout << hammingdist(S, T) << endl;
    cout << "-1 -1";
}
else if (charMap.size() == 1) {
    cout << hammingdist(S, T) - 1 << endl;
    auto iter = charMap.begin()->second.begin();
    cout << (*/*charMap.begin()->second.begin()*/iter) + 1 << ' ' << (*(++iter) + 1); // the problem is here
}
else if (charMap.size() >= 2) {
    cout << hammingdist(S, T) - 2 << endl;
    auto iter = charMap.begin()->second.begin();
    cout << ((*iter) ) << ' ' << (*(++iter) + 1);
}
}

结果是它首先递增 "iter" 然后做它的 2 个输出。 改变这个:

cout << (*iter) + 1 << ' ' << (*(++iter) + 1);

对此:

cout << (*iter) + 1 << ' ';
++iter;
cout << (*iter) + 1;

已修复。所以总而言之,这是一个计算问题,而不是设置迭代器。