I just wrote some C++ code roughly as follows:—
int i;
string out;
map<char, string>::const_iterator it;
for (i = 0; i < inp.size(); ++i) {
it = mydict.find(inp[i]);
if (it != mydict.end())
out += mydict[inp[i]];
else
out += inp[i];
}
I don’t write a lot of C++ code and I’m looking for suggestions to improve the same. I tried something as follows but I get an incompatible operand types ('mapped_type' (aka 'std::basic_string<char>') and 'char') error:
int i;
string out;
map<char, string>::const_iterator it;
for (i = 0; i < inp.size(); ++i) {
it = mydict.find(inp[i]);
out += (it != mydict.end() ? mydict[inp[i]] : inp[i]);
}
Any suggestions to correct the error above? Or any suggestions for better way to code the same?
You need to make sure that both options of the conditional assignment operator return the same type. Try this to change the character inp[i] to a string: