If I compile and run the following program with the input of "4 petr egor" I get the output of "2 2 2", but the expected output should be "2 1 2", for some reason in the second from the bottom if statement if I output *iter I get "2", and if I output *charMap.begin()->second.begin(), I get "1". Why is this happening?
#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);
}
}
Turns out that the it increments the "iter" first and then does 2 outputs of it. Changing this:
cout << (*iter) + 1 << ' ' << (*(++iter) + 1);
to this:
cout << (*iter) + 1 << ' ';
++iter;
cout << (*iter) + 1;
fixed it. So all in all it was a cout problem, not set iterator.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.