fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <iterator>
  4. #include <string>
  5.  
  6. namespace
  7. {
  8. /// {п4,a}b4c{2,p} -> aaaab4cpp
  9. template<class InputIt, class OutputIt>
  10. OutputIt rle_decode(InputIt first, InputIt last, OutputIt d_first)
  11. {
  12. while(first != last) {
  13. if (*first != '{') {
  14. *d_first++ = *first++; // copy the input to the output as is
  15. }
  16. else { // decode {count,char} RLE run
  17. ++first; // skip {
  18.  
  19. // read count
  20. uintmax_t count = 0;
  21. for ( ; first != last && '0' <= *first && *first <= '9'; ++first )
  22. count += 10 * count + (*first - '0'); //NOTE: ignore overflow
  23.  
  24. if (first == last || *first++ != ',' || first == last)
  25. throw std::invalid_argument("missing comma or char in {count,char}");
  26.  
  27. // output current character *count* times
  28. d_first = std::fill_n(d_first, count, *first++);
  29.  
  30. if (first == last || *first++ != '}')
  31. throw std::invalid_argument("expected '}'");
  32. }
  33. }
  34. return d_first;
  35. }
  36. }
  37.  
  38. int main()
  39. {
  40. std::string text = "{4,a}b4c{2,p}";
  41. std::string s;
  42. rle_decode(std::begin(text), std::end(text), std::back_inserter(s));
  43. std::cout << s << '\n';
  44.  
  45. rle_decode(std::begin(text), std::end(text), std::ostream_iterator<char>(std::cout));
  46. std::cout << '\n';
  47.  
  48. std::istream_iterator<char> chars{std::cin}, eof;
  49. rle_decode(chars, eof, std::ostream_iterator<char>(std::cout));
  50. std::cout << '\n';
  51. }
  52.  
Success #stdin #stdout 0s 15232KB
stdin
{123,a}b{1,c}
stdout
aaaab4cpp
aaaab4cpp
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabc