Does c++11 offer similar solution as implemented in python maketrans/translate?

413 views Asked by At

Does c++11 offer elegant solution as implemented in python maketrans/translate?

from string import maketrans 

intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)

str = "this is string example....wow!!!";
print str.translate(trantab);
2

There are 2 answers

4
Rufflewind On BEST ANSWER

As as I'm aware there's no built-in function for this, but you could conceivably implement one:

#include <functional>
#include <string>
#include <unordered_map>

std::function<std::string(std::string)>
maketrans(const std::string& from, const std::string& to) {
    std::unordered_map<char, char> map;
    for (std::string::size_type i = 0;
         i != std::min(from.size(), to.size()); ++i) {
        map[from[i]] = to[i];
    }
    return [=](std::string s) {
        for (auto& c : s) {
            const auto mapped_c = map.find(c);
            if (mapped_c != map.end()) {
                c = mapped_c->second;
            }
        }
        return s;
    };
}

#include <iostream>
int main() {
    const std::string intab = "aeiou";
    const std::string outtab = "12345";
    const auto translate = maketrans(intab, outtab);

    const std::string str = "this is string example....wow!!!";
    std::cout << translate(str) << std::endl;
    return 0;
}
0
luk32 On

My try. Would would need to make a helper to create the map from two strings:

#include <iostream>
#include <string>
#include <map>
using namespace std;

using TransMap = std::map<char, char>;
void translate(std::string& string, TransMap map ){
    for(auto& c : string){
        const auto itr = map.find(c);
        if(itr != map.end()) c = itr->second;
    }
}

int main() {
    std::string test = "123456789";
    TransMap map{ {'1', 'a'}, {'2', 'b'}, {'3', 'c'}, {'4', 'd'}, {'5', 'e'} };
    translate(test, map);
    std::cout << test << '\n';
    return 0;
}