2014-12-22 3 views
0

C++ 11은 파이썬 maketrans/translate에 구현 된 것처럼 우아한 솔루션을 제공합니까?C++ 11은 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); 
+0

표준 라이브러리에는 그런 내용이 없을 것이라고 생각하지만 작성하기가 너무 어려워서는 안됩니다. – luk32

답변

5

나는이에 대한 내장 함수가 없습니다 알고 있어요,하지만 당신은 생각할를 구현할 수만큼 :

#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; 
} 
+1

Whoa Kudos는 zip으로 즉석에서 '번역'을하는 기능을합니다. – luk32

+0

음. 이것은 깔끔한 코드입니다. 여기에 복잡성에 대한 의견 하나만 남았습니다. 그것은 o (1)가 아닙니다. 파이썬 maketrans/translate는 o (1)라고 생각합니다. 10x – idanshmu

+0

O (1)과 관련하여? 복잡성에 관해서는 가능한 한 효율적입니다. (입력 길이에 대해 선형입니다.) – Rufflewind

1

내 시도. 두 문자열에서지도를 만드는 데 도우미를 만들어야합니다.

#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; 
}