提供的答案是正确的,但是operator[]对于相同的密钥使用两次,这不是免费的,可以避免:
std::map<char, std::string> a;
Run Code Online (Sandbox Code Playgroud)
解决方案1:
std::string &item1 = a['a'];
std::string &item2 = a['b'];
std::swap(item1, item2);
Run Code Online (Sandbox Code Playgroud)
解决方案2:
const std::map<char, std::string>::iterator item1 = a.find('a');
const std::map<char, std::string>::iterator item2 = a.find('b');
if ((item1 != a.end()) && (item2 != a.end()))
std::swap(item1->second, item2->second);
Run Code Online (Sandbox Code Playgroud)
当然,这两个解决方案不是等价的(解决方案2只交换已经在映射中的值,解决方案1插入而不会产生疑问,最终可能会交换两个默认构造的字符串).