String manipulation with std::adjacent_findConverting between std::wstring and std::stringstd::vector memory manipulation with serialization and deserializationString manipulation in JavaStreambuffer and string manipulationMimic sprintf with std::string outputHomebrew std::string for use with kernelPrinting doubles using string manipulationDetermining if an std::string contains a numerical typeStudent class with std::stringstd::string implementation attempt

Diagonal arrows (using TikZ) should be aligned in parallel

This one's for Matthew:

When an electron changes its spin, or any other intrinsic property, is it still the same electron?

What were the main German words for a prostitute before 1800?

Does Multiverse exist in MCU?

How do native German speakers usually express skepticism (using even) about a premise?

Is there any reason why MCU changed the Snap to Blip

Why do we need common sense in AI?

Is a request to book a business flight ticket for a graduate student an unreasonable one?

How to say "How long have you had this dream?"

Placing text inside a loop

Word meaning to destroy books

How can a dictatorship government be beneficial to a dictator in a post-scarcity society?

Is it OK to leave real names & info visible in business card portfolio?

When I press the space bar it deletes the letters after it

Would dual wielding daggers be a viable choice for a covert bodyguard?

Swapping "Good" and "Bad"

Shortest hex dumping program

How to trigger Authentification of Named Credential created via Apex

How to tell someone I'd like to become friends without letting them think I'm romantically interested in them?

Does the Pole of Angling's command word require an action?

Why isn't pressure filtration popular compared to vacuum filtration?

Does throwing a penny at a train stop the train?

How were Martello towers supposed to work?



String manipulation with std::adjacent_find


Converting between std::wstring and std::stringstd::vector memory manipulation with serialization and deserializationString manipulation in JavaStreambuffer and string manipulationMimic sprintf with std::string outputHomebrew std::string for use with kernelPrinting doubles using string manipulationDetermining if an std::string contains a numerical typeStudent class with std::stringstd::string implementation attempt






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








5












$begingroup$



For the given strings (not containing numbers), print their shortened
versions, where each adjacent sequence of the same characters longer
than 2, change to an expression consisting of a sign and a number of
repetitions.




Sample input:



4
AAA
ABCDEF
CCCCCCDDDDDDD
ZZAACCCDDDDEEEEEE


Sample output:



A3
ABCDEF
C6D7
ZZAAC3D4E6


My code:



#include <algorithm>
#include <cstddef>
#include <functional>
#include <iostream>
#include <iterator>
#include <string>

std::string reduce(std::string const& word)
std::string result;
for (auto it = word.cbegin(); true;)
auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to<int>());
auto dist = std::distance(it, curr) + (curr != word.cend());

if (dist < 3)
result += std::string(dist, *it);
else
result += *it + std::to_string(dist);


if (curr == word.cend())
break;

it = 1 + curr;

return result;


int main()
std::size_t tests;
std::cin >> tests;
while (tests--)
std::string word;
std::cin >> word;
std::cout << reduce(word) << "n";




How could I simplify or improve this code?










share|improve this question









New contributor



Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






$endgroup$


















    5












    $begingroup$



    For the given strings (not containing numbers), print their shortened
    versions, where each adjacent sequence of the same characters longer
    than 2, change to an expression consisting of a sign and a number of
    repetitions.




    Sample input:



    4
    AAA
    ABCDEF
    CCCCCCDDDDDDD
    ZZAACCCDDDDEEEEEE


    Sample output:



    A3
    ABCDEF
    C6D7
    ZZAAC3D4E6


    My code:



    #include <algorithm>
    #include <cstddef>
    #include <functional>
    #include <iostream>
    #include <iterator>
    #include <string>

    std::string reduce(std::string const& word)
    std::string result;
    for (auto it = word.cbegin(); true;)
    auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to<int>());
    auto dist = std::distance(it, curr) + (curr != word.cend());

    if (dist < 3)
    result += std::string(dist, *it);
    else
    result += *it + std::to_string(dist);


    if (curr == word.cend())
    break;

    it = 1 + curr;

    return result;


    int main()
    std::size_t tests;
    std::cin >> tests;
    while (tests--)
    std::string word;
    std::cin >> word;
    std::cout << reduce(word) << "n";




    How could I simplify or improve this code?










    share|improve this question









    New contributor



    Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






    $endgroup$














      5












      5








      5





      $begingroup$



      For the given strings (not containing numbers), print their shortened
      versions, where each adjacent sequence of the same characters longer
      than 2, change to an expression consisting of a sign and a number of
      repetitions.




      Sample input:



      4
      AAA
      ABCDEF
      CCCCCCDDDDDDD
      ZZAACCCDDDDEEEEEE


      Sample output:



      A3
      ABCDEF
      C6D7
      ZZAAC3D4E6


      My code:



      #include <algorithm>
      #include <cstddef>
      #include <functional>
      #include <iostream>
      #include <iterator>
      #include <string>

      std::string reduce(std::string const& word)
      std::string result;
      for (auto it = word.cbegin(); true;)
      auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to<int>());
      auto dist = std::distance(it, curr) + (curr != word.cend());

      if (dist < 3)
      result += std::string(dist, *it);
      else
      result += *it + std::to_string(dist);


      if (curr == word.cend())
      break;

      it = 1 + curr;

      return result;


      int main()
      std::size_t tests;
      std::cin >> tests;
      while (tests--)
      std::string word;
      std::cin >> word;
      std::cout << reduce(word) << "n";




      How could I simplify or improve this code?










      share|improve this question









      New contributor



      Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      $endgroup$





      For the given strings (not containing numbers), print their shortened
      versions, where each adjacent sequence of the same characters longer
      than 2, change to an expression consisting of a sign and a number of
      repetitions.




      Sample input:



      4
      AAA
      ABCDEF
      CCCCCCDDDDDDD
      ZZAACCCDDDDEEEEEE


      Sample output:



      A3
      ABCDEF
      C6D7
      ZZAAC3D4E6


      My code:



      #include <algorithm>
      #include <cstddef>
      #include <functional>
      #include <iostream>
      #include <iterator>
      #include <string>

      std::string reduce(std::string const& word)
      std::string result;
      for (auto it = word.cbegin(); true;)
      auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to<int>());
      auto dist = std::distance(it, curr) + (curr != word.cend());

      if (dist < 3)
      result += std::string(dist, *it);
      else
      result += *it + std::to_string(dist);


      if (curr == word.cend())
      break;

      it = 1 + curr;

      return result;


      int main()
      std::size_t tests;
      std::cin >> tests;
      while (tests--)
      std::string word;
      std::cin >> word;
      std::cout << reduce(word) << "n";




      How could I simplify or improve this code?







      c++ programming-challenge strings c++14






      share|improve this question









      New contributor



      Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share|improve this question









      New contributor



      Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share|improve this question




      share|improve this question








      edited 9 hours ago







      Dessus













      New contributor



      Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      asked 9 hours ago









      DessusDessus

      263 bronze badges




      263 bronze badges




      New contributor



      Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




      New contributor




      Dessus is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          2 Answers
          2






          active

          oldest

          votes


















          3












          $begingroup$

          First impressions: nicely presented code; good use of the appropriate standard library functions and classes.



          A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>). Perhaps call it compress?



          I'd suggest extracting the constant 3 to give it a meaningful name.



          Can we eliminate the break with some reorganisation of the loop? Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()? (I haven't fully thought that through; it might not be better.)



          We can avoid constructing a new string here:




           result += std::string(dist, *it);



          by using the overload of append() that takes two iterators:



           result.append(dist, *it);





          share|improve this answer









          $endgroup$




















            0












            $begingroup$

            A few things might be better, but you will need to measure if they actually help. (untested code)



            The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try



            result.reserve(word.size());


            and



            constexpr int LargeBuffer 4096 ;
            std::string word;
            word.reserve(LargeBuffer); // reuse the buffer.
            while (tests--)
            std::cin >> word;
            std::cout << reduce(word) << "n"; // this call might use NRVO



            That might still trigger one allocation per word, so a more drastic rebuild could be



            std::string& reduce(std::string const& word, std::string & result)


            and



            constexpr int LargeBuffer 4096 ;
            std::string word, result;
            word.reserve(LargeBuffer); // reuse the buffer.
            result.reserve(LargeBuffer);
            while (tests--)
            std::cin >> word;
            result.clear(); // should not dealloc.
            std::cout << reduce(word, result) << "n";



            The strings will grow and keep their new size if the actual word is larger than expected.



            The next most expensive should be the std::to_string



             if (dist < 3) 
            result.append(dist, *it); // from Toby's answer
            else
            result.append(*it);
            if (dist < 10)
            result.append('0'+dist);
            else
            result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation




            The change should work nicely for your example data, less so if the repeats randomly change between <10 and >= 10.






            share|improve this answer









            $endgroup$















              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "196"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );






              Dessus is a new contributor. Be nice, and check out our Code of Conduct.









              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f223812%2fstring-manipulation-with-stdadjacent-find%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              3












              $begingroup$

              First impressions: nicely presented code; good use of the appropriate standard library functions and classes.



              A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>). Perhaps call it compress?



              I'd suggest extracting the constant 3 to give it a meaningful name.



              Can we eliminate the break with some reorganisation of the loop? Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()? (I haven't fully thought that through; it might not be better.)



              We can avoid constructing a new string here:




               result += std::string(dist, *it);



              by using the overload of append() that takes two iterators:



               result.append(dist, *it);





              share|improve this answer









              $endgroup$

















                3












                $begingroup$

                First impressions: nicely presented code; good use of the appropriate standard library functions and classes.



                A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>). Perhaps call it compress?



                I'd suggest extracting the constant 3 to give it a meaningful name.



                Can we eliminate the break with some reorganisation of the loop? Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()? (I haven't fully thought that through; it might not be better.)



                We can avoid constructing a new string here:




                 result += std::string(dist, *it);



                by using the overload of append() that takes two iterators:



                 result.append(dist, *it);





                share|improve this answer









                $endgroup$















                  3












                  3








                  3





                  $begingroup$

                  First impressions: nicely presented code; good use of the appropriate standard library functions and classes.



                  A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>). Perhaps call it compress?



                  I'd suggest extracting the constant 3 to give it a meaningful name.



                  Can we eliminate the break with some reorganisation of the loop? Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()? (I haven't fully thought that through; it might not be better.)



                  We can avoid constructing a new string here:




                   result += std::string(dist, *it);



                  by using the overload of append() that takes two iterators:



                   result.append(dist, *it);





                  share|improve this answer









                  $endgroup$



                  First impressions: nicely presented code; good use of the appropriate standard library functions and classes.



                  A minor suggestion would be to change the name, given that reduce is a well-known concept in functional programming (and is a function in <numeric>). Perhaps call it compress?



                  I'd suggest extracting the constant 3 to give it a meaningful name.



                  Can we eliminate the break with some reorganisation of the loop? Perhaps by using std::mismatch(it, it+1) instead of std::adjacent_find()? (I haven't fully thought that through; it might not be better.)



                  We can avoid constructing a new string here:




                   result += std::string(dist, *it);



                  by using the overload of append() that takes two iterators:



                   result.append(dist, *it);






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 8 hours ago









                  Toby SpeightToby Speight

                  30.5k7 gold badges45 silver badges132 bronze badges




                  30.5k7 gold badges45 silver badges132 bronze badges























                      0












                      $begingroup$

                      A few things might be better, but you will need to measure if they actually help. (untested code)



                      The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try



                      result.reserve(word.size());


                      and



                      constexpr int LargeBuffer 4096 ;
                      std::string word;
                      word.reserve(LargeBuffer); // reuse the buffer.
                      while (tests--)
                      std::cin >> word;
                      std::cout << reduce(word) << "n"; // this call might use NRVO



                      That might still trigger one allocation per word, so a more drastic rebuild could be



                      std::string& reduce(std::string const& word, std::string & result)


                      and



                      constexpr int LargeBuffer 4096 ;
                      std::string word, result;
                      word.reserve(LargeBuffer); // reuse the buffer.
                      result.reserve(LargeBuffer);
                      while (tests--)
                      std::cin >> word;
                      result.clear(); // should not dealloc.
                      std::cout << reduce(word, result) << "n";



                      The strings will grow and keep their new size if the actual word is larger than expected.



                      The next most expensive should be the std::to_string



                       if (dist < 3) 
                      result.append(dist, *it); // from Toby's answer
                      else
                      result.append(*it);
                      if (dist < 10)
                      result.append('0'+dist);
                      else
                      result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation




                      The change should work nicely for your example data, less so if the repeats randomly change between <10 and >= 10.






                      share|improve this answer









                      $endgroup$

















                        0












                        $begingroup$

                        A few things might be better, but you will need to measure if they actually help. (untested code)



                        The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try



                        result.reserve(word.size());


                        and



                        constexpr int LargeBuffer 4096 ;
                        std::string word;
                        word.reserve(LargeBuffer); // reuse the buffer.
                        while (tests--)
                        std::cin >> word;
                        std::cout << reduce(word) << "n"; // this call might use NRVO



                        That might still trigger one allocation per word, so a more drastic rebuild could be



                        std::string& reduce(std::string const& word, std::string & result)


                        and



                        constexpr int LargeBuffer 4096 ;
                        std::string word, result;
                        word.reserve(LargeBuffer); // reuse the buffer.
                        result.reserve(LargeBuffer);
                        while (tests--)
                        std::cin >> word;
                        result.clear(); // should not dealloc.
                        std::cout << reduce(word, result) << "n";



                        The strings will grow and keep their new size if the actual word is larger than expected.



                        The next most expensive should be the std::to_string



                         if (dist < 3) 
                        result.append(dist, *it); // from Toby's answer
                        else
                        result.append(*it);
                        if (dist < 10)
                        result.append('0'+dist);
                        else
                        result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation




                        The change should work nicely for your example data, less so if the repeats randomly change between <10 and >= 10.






                        share|improve this answer









                        $endgroup$















                          0












                          0








                          0





                          $begingroup$

                          A few things might be better, but you will need to measure if they actually help. (untested code)



                          The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try



                          result.reserve(word.size());


                          and



                          constexpr int LargeBuffer 4096 ;
                          std::string word;
                          word.reserve(LargeBuffer); // reuse the buffer.
                          while (tests--)
                          std::cin >> word;
                          std::cout << reduce(word) << "n"; // this call might use NRVO



                          That might still trigger one allocation per word, so a more drastic rebuild could be



                          std::string& reduce(std::string const& word, std::string & result)


                          and



                          constexpr int LargeBuffer 4096 ;
                          std::string word, result;
                          word.reserve(LargeBuffer); // reuse the buffer.
                          result.reserve(LargeBuffer);
                          while (tests--)
                          std::cin >> word;
                          result.clear(); // should not dealloc.
                          std::cout << reduce(word, result) << "n";



                          The strings will grow and keep their new size if the actual word is larger than expected.



                          The next most expensive should be the std::to_string



                           if (dist < 3) 
                          result.append(dist, *it); // from Toby's answer
                          else
                          result.append(*it);
                          if (dist < 10)
                          result.append('0'+dist);
                          else
                          result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation




                          The change should work nicely for your example data, less so if the repeats randomly change between <10 and >= 10.






                          share|improve this answer









                          $endgroup$



                          A few things might be better, but you will need to measure if they actually help. (untested code)



                          The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try



                          result.reserve(word.size());


                          and



                          constexpr int LargeBuffer 4096 ;
                          std::string word;
                          word.reserve(LargeBuffer); // reuse the buffer.
                          while (tests--)
                          std::cin >> word;
                          std::cout << reduce(word) << "n"; // this call might use NRVO



                          That might still trigger one allocation per word, so a more drastic rebuild could be



                          std::string& reduce(std::string const& word, std::string & result)


                          and



                          constexpr int LargeBuffer 4096 ;
                          std::string word, result;
                          word.reserve(LargeBuffer); // reuse the buffer.
                          result.reserve(LargeBuffer);
                          while (tests--)
                          std::cin >> word;
                          result.clear(); // should not dealloc.
                          std::cout << reduce(word, result) << "n";



                          The strings will grow and keep their new size if the actual word is larger than expected.



                          The next most expensive should be the std::to_string



                           if (dist < 3) 
                          result.append(dist, *it); // from Toby's answer
                          else
                          result.append(*it);
                          if (dist < 10)
                          result.append('0'+dist);
                          else
                          result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation




                          The change should work nicely for your example data, less so if the repeats randomly change between <10 and >= 10.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 2 hours ago









                          SurtSurt

                          5022 silver badges8 bronze badges




                          5022 silver badges8 bronze badges




















                              Dessus is a new contributor. Be nice, and check out our Code of Conduct.









                              draft saved

                              draft discarded


















                              Dessus is a new contributor. Be nice, and check out our Code of Conduct.












                              Dessus is a new contributor. Be nice, and check out our Code of Conduct.











                              Dessus is a new contributor. Be nice, and check out our Code of Conduct.














                              Thanks for contributing an answer to Code Review Stack Exchange!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              Use MathJax to format equations. MathJax reference.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f223812%2fstring-manipulation-with-stdadjacent-find%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Sahara Skak | Bilen | Luke uk diar | NawigatsjuunCommonskategorii: SaharaWikivoyage raisfeerer: Sahara26° N, 13° O

                              The fall designs the understood secretary. Looking glass Science Shock Discovery Hot Everybody Loves Raymond Smile 곳 서비스 성실하다 Defas Kaloolon Definition: To combine or impregnate with sulphur or any of its compounds as to sulphurize caoutchouc in vulcanizing Flame colored Reason Useful Thin Help 갖다 유명하다 낙엽 장례식 Country Iron Definition: A fencer a gladiator one who exhibits his skill in the use of the sword Definition: The American black throated bunting Spiza Americana Nostalgic Needy Method to my madness 시키다 평가되다 전부 소설가 우아하다 Argument Tin Feeling Representative Gym Music Gaur Chicken 일쑤 코치 편 학생증 The harbor values the sugar. Vasagle Yammoe Enstatite Definition: Capable of being limited Road Neighborly Five Refer Built Kangaroo 비비다 Degree Release Bargain Horse 하루 형님 유교 석 동부 괴롭히다 경제력

                              19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу