替换字符串中的多对字符

Replace multiple pair of characters in string

我想用 'b' 替换所有出现的 'a',用 'd' 替换 'c'。

我目前的解决方案是:

std::replace(str.begin(), str.end(), 'a', 'b');
std::replace(str.begin(), str.end(), 'c', 'd');

是否可以使用 std 在单个函数中完成?

如果不喜欢两次pass,可以一次:

 std::transform(std::begin(s), std::end(s), std::begin(s), [](auto ch) {
    switch (ch) {
    case 'a':
      return 'b';
    case 'c':
      return 'd';
    }
    return ch;
  });

棘手的解决方案:

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

int main() {
   char r; //replacement
   std::map<char, char> rs = { {'a', 'b'}, {'c', 'd'} };
   std::string s = "abracadabra";
   std::replace_if(s.begin(), s.end(), [&](char c){ return r = rs[c]; }, r);
   std::cout << s << std::endl;
}

编辑

为了取悦所有效率激进分子,可以更改解决方案,不为每个不存在的键附加 rs 映射,同时保持棘手的味道不变。这可以按如下方式完成:

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

int main() {
   char r; //replacement
   std::map<char, char> rs = { {'a', 'b'}, {'c', 'd'} };
   std::string s = "abracadabra";
   std::replace_if(s.begin(), s.end(), [&](char c){ return (rs.find(c) != rs.end())
                                                        && (r = rs[c]); }, r); 
   std::cout << s << std::endl; //bbrbdbdbbrb
}

[live demo]