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');
std::replace(str.begin(), str.end(), 'c', 'd');
Is it possible do it in single function using the std?
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');
std::replace(str.begin(), str.end(), 'c', 'd');
Is it possible do it in single function using the std?
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
}
std::map::operator[] newly appends a default constructed element to the map itself if the corresponding value to the given key does not exist. So with this solution by @W.F, the size of rs increases as the number of unmatched characters.