I want to replace all occurrence of \'a\' with \'b\', and \'c\' with \'d\'.
My current solution is:
std::replace(str.begin(), str.end(), \'a\', \'b\'
If you do not like two passes, you can do it once:
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;
});
Tricky solution:
#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;
}
Edit
To please all efficiency radicals one can change the solution, to not to append rs
map for each non existing key, while remain tricky flavor untouched. This can be done as follows:
#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]