user277465
user277465

Reputation:

More concise C++ version possible?

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?

Upvotes: 1

Views: 179

Answers (2)

Matthieu M.
Matthieu M.

Reputation: 299810

In C++11 you could simplify the looping construct itself:

for (char c: inp) {
    auto it = mydict.find(c);
    it != mydict.end() ? out += it->second : out += c; // little known use ;)
}

Other than that, I advise you to use it->second instead of performing the lookup for c once again.

Upvotes: 6

Darius Makaitis
Darius Makaitis

Reputation: 880

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:

out += (it != mydict.end() ? mydict[inp[i]] : string(1, inp[i]));

Upvotes: 3

Related Questions