Performance issue in code for reading line and testing for palindromeCheck if the string is palindromeCheck if a string is palindrome or two strings are the opposite of each otherTesting input integers for the palindrome propertyChecking for a palindromeMilliseconds to Time string & Time string to MillisecondsLongest Common Subsequence and Longest Subsequence PalindromeComparing a string using a stackCheck for Palindrome string in JavaLeetcode 125. Valid Palindrome (better performance?)Palindrome-testing Java program for an interviewPalindrome implementations - iterative and recursiveMatch a simple balanced language using a queue

Performance issue in code for reading line and testing for palindrome

Generalized Behrend version for Grothendieck-Lefschetz trace formula

I make billions (#6)

Is this Cambridge Dictionary example of "felicitate" valid?

Non-Chromatic Orchestral Instruments?

Red token deck mass token destruction enchantment protection mtg

Why did Old English lose both thorn and eth?

Why is the Cauchy Distribution is so useful?

Correct notation for guitar fingerstyle

Estimates on number of topologies on a finite set

Did Rabbi Akiva accept arguments from ignorance?

What are the effects of abstaining from eating a certain flavor?

Writing an ace/aro character?

Adjust the Table

Any unique interactions, with an Altmer Dragonborn?

Distinguish the explanations of Galadriel's test in LotR

Why did Dumbledore ignore this line?

What do you call a situation where you have choices but no good choice?

Why was such an unrevealing title originally chosen and then changed for some International markets?

How was the Shuttle loaded and unloaded from its carrier aircraft?

Password Hashing Security Using Scrypt & Argon2

No Torah = Revert to Nothingness?

How insert vertex in face?

Category-theoretic treatment of diffs, patches and merging?



Performance issue in code for reading line and testing for palindrome


Check if the string is palindromeCheck if a string is palindrome or two strings are the opposite of each otherTesting input integers for the palindrome propertyChecking for a palindromeMilliseconds to Time string & Time string to MillisecondsLongest Common Subsequence and Longest Subsequence PalindromeComparing a string using a stackCheck for Palindrome string in JavaLeetcode 125. Valid Palindrome (better performance?)Palindrome-testing Java program for an interviewPalindrome implementations - iterative and recursiveMatch a simple balanced language using a queue






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








2












$begingroup$


This is some code that determines if a string of characters is a palindrome or not. My professor says that there is a performance issue with the program, but I can't quite put my finger on it. Can someone find out the 'performance' issue?



Initially, I thought maybe the process is slower as it uses two memory containers, as opposed to simply comparing two halves of a single string.



int main()

char c;
bool check = true;
stack<char> cstack;
queue<char> cqueue;
cout << "Enter a string and press return." << endl;
cin.get(c);
while (c != 'n')
cstack.push(c);
cqueue.push(c);
cin.get(c);

while (check && !cqueue.empty())
if (cstack.top() != cqueue.front())
check = false;
cstack.pop();
cqueue.pop();

if (check)
cout << "Yes it is!" << endl;
else
cout << "No it's not." << endl;
return 0;










share|improve this question









New contributor



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






$endgroup$











  • $begingroup$
    Is there a way to combine stack top/pop and queue front/pop in a single statement?
    $endgroup$
    – dfhwze
    8 hours ago










  • $begingroup$
    You might want to have a look at this, though in that case the check was case insensitive.
    $endgroup$
    – Incomputable
    5 hours ago






  • 3




    $begingroup$
    As an aside, this is nearly a complete program. Consider giving the full program next time in a similar situation (changing this now is inadvisable).
    $endgroup$
    – Deduplicator
    5 hours ago

















2












$begingroup$


This is some code that determines if a string of characters is a palindrome or not. My professor says that there is a performance issue with the program, but I can't quite put my finger on it. Can someone find out the 'performance' issue?



Initially, I thought maybe the process is slower as it uses two memory containers, as opposed to simply comparing two halves of a single string.



int main()

char c;
bool check = true;
stack<char> cstack;
queue<char> cqueue;
cout << "Enter a string and press return." << endl;
cin.get(c);
while (c != 'n')
cstack.push(c);
cqueue.push(c);
cin.get(c);

while (check && !cqueue.empty())
if (cstack.top() != cqueue.front())
check = false;
cstack.pop();
cqueue.pop();

if (check)
cout << "Yes it is!" << endl;
else
cout << "No it's not." << endl;
return 0;










share|improve this question









New contributor



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






$endgroup$











  • $begingroup$
    Is there a way to combine stack top/pop and queue front/pop in a single statement?
    $endgroup$
    – dfhwze
    8 hours ago










  • $begingroup$
    You might want to have a look at this, though in that case the check was case insensitive.
    $endgroup$
    – Incomputable
    5 hours ago






  • 3




    $begingroup$
    As an aside, this is nearly a complete program. Consider giving the full program next time in a similar situation (changing this now is inadvisable).
    $endgroup$
    – Deduplicator
    5 hours ago













2












2








2





$begingroup$


This is some code that determines if a string of characters is a palindrome or not. My professor says that there is a performance issue with the program, but I can't quite put my finger on it. Can someone find out the 'performance' issue?



Initially, I thought maybe the process is slower as it uses two memory containers, as opposed to simply comparing two halves of a single string.



int main()

char c;
bool check = true;
stack<char> cstack;
queue<char> cqueue;
cout << "Enter a string and press return." << endl;
cin.get(c);
while (c != 'n')
cstack.push(c);
cqueue.push(c);
cin.get(c);

while (check && !cqueue.empty())
if (cstack.top() != cqueue.front())
check = false;
cstack.pop();
cqueue.pop();

if (check)
cout << "Yes it is!" << endl;
else
cout << "No it's not." << endl;
return 0;










share|improve this question









New contributor



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






$endgroup$




This is some code that determines if a string of characters is a palindrome or not. My professor says that there is a performance issue with the program, but I can't quite put my finger on it. Can someone find out the 'performance' issue?



Initially, I thought maybe the process is slower as it uses two memory containers, as opposed to simply comparing two halves of a single string.



int main()

char c;
bool check = true;
stack<char> cstack;
queue<char> cqueue;
cout << "Enter a string and press return." << endl;
cin.get(c);
while (c != 'n')
cstack.push(c);
cqueue.push(c);
cin.get(c);

while (check && !cqueue.empty())
if (cstack.top() != cqueue.front())
check = false;
cstack.pop();
cqueue.pop();

if (check)
cout << "Yes it is!" << endl;
else
cout << "No it's not." << endl;
return 0;







c++ performance beginner strings palindrome






share|improve this question









New contributor



Avantika P 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



Avantika P 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 5 hours ago









Deduplicator

12.9k20 silver badges52 bronze badges




12.9k20 silver badges52 bronze badges






New contributor



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








asked 8 hours ago









Avantika PAvantika P

162 bronze badges




162 bronze badges




New contributor



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




New contributor




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













  • $begingroup$
    Is there a way to combine stack top/pop and queue front/pop in a single statement?
    $endgroup$
    – dfhwze
    8 hours ago










  • $begingroup$
    You might want to have a look at this, though in that case the check was case insensitive.
    $endgroup$
    – Incomputable
    5 hours ago






  • 3




    $begingroup$
    As an aside, this is nearly a complete program. Consider giving the full program next time in a similar situation (changing this now is inadvisable).
    $endgroup$
    – Deduplicator
    5 hours ago
















  • $begingroup$
    Is there a way to combine stack top/pop and queue front/pop in a single statement?
    $endgroup$
    – dfhwze
    8 hours ago










  • $begingroup$
    You might want to have a look at this, though in that case the check was case insensitive.
    $endgroup$
    – Incomputable
    5 hours ago






  • 3




    $begingroup$
    As an aside, this is nearly a complete program. Consider giving the full program next time in a similar situation (changing this now is inadvisable).
    $endgroup$
    – Deduplicator
    5 hours ago















$begingroup$
Is there a way to combine stack top/pop and queue front/pop in a single statement?
$endgroup$
– dfhwze
8 hours ago




$begingroup$
Is there a way to combine stack top/pop and queue front/pop in a single statement?
$endgroup$
– dfhwze
8 hours ago












$begingroup$
You might want to have a look at this, though in that case the check was case insensitive.
$endgroup$
– Incomputable
5 hours ago




$begingroup$
You might want to have a look at this, though in that case the check was case insensitive.
$endgroup$
– Incomputable
5 hours ago




3




3




$begingroup$
As an aside, this is nearly a complete program. Consider giving the full program next time in a similar situation (changing this now is inadvisable).
$endgroup$
– Deduplicator
5 hours ago




$begingroup$
As an aside, this is nearly a complete program. Consider giving the full program next time in a similar situation (changing this now is inadvisable).
$endgroup$
– Deduplicator
5 hours ago










2 Answers
2






active

oldest

votes


















3












$begingroup$

  1. While it is not quite definitive, it looks like you use using namespace std;.

    That namespace is not designed for wholesale inclusion, being vast and subject to change at the whim of the implementation, aside from providing what is standardised.

    Read "Why is “using namespace std” considered bad practice?" for more detail.


  2. You should desist from using std::endl, as spurious manual flushing flushes any pretense at performance down the drain.

    For those rare cases where it is actually necessary for correctness, use std::flush for explicitness.


  3. You assume reading from std::cin always succeeds. That's generally unsupportable, please handle failure gracefully.


  4. You are reading character-by-character. Each and every read has significant overhead, which you could simply avoid by using std::getline(). Using the proper abstraction is also significantly more readable.


  5. You are storing the input twice, once in a std::queue and once in a std::stack. Even only storing it in just one std::deque (the underlying implementation for both) would be a considerable improvement.


  6. Consider encapsulating the test whether the input is a palindrome into its own reusable function, separate from actually getting it.


  7. Testing whether something is a palindrome seems a favorite passtime of many beginners.

    Thus, there are a myriad posts on how to efficiently and elegantly do that in C++, for example "Check if a string is palindrome or two strings are the opposite of each other".

    The important points are avoiding expensive copies, and only comparing each element once.


  8. If you want one of two values, conditional on some expression, consider the conditional operator expr ? true_expr : false_expr. It is designed for that.


  9. return 0; is implicit for main(). Make of that what you will.






share|improve this answer









$endgroup$




















    2












    $begingroup$

    I see two improvement points in the code.



    1. It is better to use getLine() and store the input in char* instead of reading each char and appending to a stack

    2. It is more than enough to iterate till half of the string as the remaining half is checked in the first half iteration cstack.top() != cqueue.front()





    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
      );



      );






      Avantika P 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%2f223680%2fperformance-issue-in-code-for-reading-line-and-testing-for-palindrome%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$

      1. While it is not quite definitive, it looks like you use using namespace std;.

        That namespace is not designed for wholesale inclusion, being vast and subject to change at the whim of the implementation, aside from providing what is standardised.

        Read "Why is “using namespace std” considered bad practice?" for more detail.


      2. You should desist from using std::endl, as spurious manual flushing flushes any pretense at performance down the drain.

        For those rare cases where it is actually necessary for correctness, use std::flush for explicitness.


      3. You assume reading from std::cin always succeeds. That's generally unsupportable, please handle failure gracefully.


      4. You are reading character-by-character. Each and every read has significant overhead, which you could simply avoid by using std::getline(). Using the proper abstraction is also significantly more readable.


      5. You are storing the input twice, once in a std::queue and once in a std::stack. Even only storing it in just one std::deque (the underlying implementation for both) would be a considerable improvement.


      6. Consider encapsulating the test whether the input is a palindrome into its own reusable function, separate from actually getting it.


      7. Testing whether something is a palindrome seems a favorite passtime of many beginners.

        Thus, there are a myriad posts on how to efficiently and elegantly do that in C++, for example "Check if a string is palindrome or two strings are the opposite of each other".

        The important points are avoiding expensive copies, and only comparing each element once.


      8. If you want one of two values, conditional on some expression, consider the conditional operator expr ? true_expr : false_expr. It is designed for that.


      9. return 0; is implicit for main(). Make of that what you will.






      share|improve this answer









      $endgroup$

















        3












        $begingroup$

        1. While it is not quite definitive, it looks like you use using namespace std;.

          That namespace is not designed for wholesale inclusion, being vast and subject to change at the whim of the implementation, aside from providing what is standardised.

          Read "Why is “using namespace std” considered bad practice?" for more detail.


        2. You should desist from using std::endl, as spurious manual flushing flushes any pretense at performance down the drain.

          For those rare cases where it is actually necessary for correctness, use std::flush for explicitness.


        3. You assume reading from std::cin always succeeds. That's generally unsupportable, please handle failure gracefully.


        4. You are reading character-by-character. Each and every read has significant overhead, which you could simply avoid by using std::getline(). Using the proper abstraction is also significantly more readable.


        5. You are storing the input twice, once in a std::queue and once in a std::stack. Even only storing it in just one std::deque (the underlying implementation for both) would be a considerable improvement.


        6. Consider encapsulating the test whether the input is a palindrome into its own reusable function, separate from actually getting it.


        7. Testing whether something is a palindrome seems a favorite passtime of many beginners.

          Thus, there are a myriad posts on how to efficiently and elegantly do that in C++, for example "Check if a string is palindrome or two strings are the opposite of each other".

          The important points are avoiding expensive copies, and only comparing each element once.


        8. If you want one of two values, conditional on some expression, consider the conditional operator expr ? true_expr : false_expr. It is designed for that.


        9. return 0; is implicit for main(). Make of that what you will.






        share|improve this answer









        $endgroup$















          3












          3








          3





          $begingroup$

          1. While it is not quite definitive, it looks like you use using namespace std;.

            That namespace is not designed for wholesale inclusion, being vast and subject to change at the whim of the implementation, aside from providing what is standardised.

            Read "Why is “using namespace std” considered bad practice?" for more detail.


          2. You should desist from using std::endl, as spurious manual flushing flushes any pretense at performance down the drain.

            For those rare cases where it is actually necessary for correctness, use std::flush for explicitness.


          3. You assume reading from std::cin always succeeds. That's generally unsupportable, please handle failure gracefully.


          4. You are reading character-by-character. Each and every read has significant overhead, which you could simply avoid by using std::getline(). Using the proper abstraction is also significantly more readable.


          5. You are storing the input twice, once in a std::queue and once in a std::stack. Even only storing it in just one std::deque (the underlying implementation for both) would be a considerable improvement.


          6. Consider encapsulating the test whether the input is a palindrome into its own reusable function, separate from actually getting it.


          7. Testing whether something is a palindrome seems a favorite passtime of many beginners.

            Thus, there are a myriad posts on how to efficiently and elegantly do that in C++, for example "Check if a string is palindrome or two strings are the opposite of each other".

            The important points are avoiding expensive copies, and only comparing each element once.


          8. If you want one of two values, conditional on some expression, consider the conditional operator expr ? true_expr : false_expr. It is designed for that.


          9. return 0; is implicit for main(). Make of that what you will.






          share|improve this answer









          $endgroup$



          1. While it is not quite definitive, it looks like you use using namespace std;.

            That namespace is not designed for wholesale inclusion, being vast and subject to change at the whim of the implementation, aside from providing what is standardised.

            Read "Why is “using namespace std” considered bad practice?" for more detail.


          2. You should desist from using std::endl, as spurious manual flushing flushes any pretense at performance down the drain.

            For those rare cases where it is actually necessary for correctness, use std::flush for explicitness.


          3. You assume reading from std::cin always succeeds. That's generally unsupportable, please handle failure gracefully.


          4. You are reading character-by-character. Each and every read has significant overhead, which you could simply avoid by using std::getline(). Using the proper abstraction is also significantly more readable.


          5. You are storing the input twice, once in a std::queue and once in a std::stack. Even only storing it in just one std::deque (the underlying implementation for both) would be a considerable improvement.


          6. Consider encapsulating the test whether the input is a palindrome into its own reusable function, separate from actually getting it.


          7. Testing whether something is a palindrome seems a favorite passtime of many beginners.

            Thus, there are a myriad posts on how to efficiently and elegantly do that in C++, for example "Check if a string is palindrome or two strings are the opposite of each other".

            The important points are avoiding expensive copies, and only comparing each element once.


          8. If you want one of two values, conditional on some expression, consider the conditional operator expr ? true_expr : false_expr. It is designed for that.


          9. return 0; is implicit for main(). Make of that what you will.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 5 hours ago









          DeduplicatorDeduplicator

          12.9k20 silver badges52 bronze badges




          12.9k20 silver badges52 bronze badges























              2












              $begingroup$

              I see two improvement points in the code.



              1. It is better to use getLine() and store the input in char* instead of reading each char and appending to a stack

              2. It is more than enough to iterate till half of the string as the remaining half is checked in the first half iteration cstack.top() != cqueue.front()





              share|improve this answer









              $endgroup$

















                2












                $begingroup$

                I see two improvement points in the code.



                1. It is better to use getLine() and store the input in char* instead of reading each char and appending to a stack

                2. It is more than enough to iterate till half of the string as the remaining half is checked in the first half iteration cstack.top() != cqueue.front()





                share|improve this answer









                $endgroup$















                  2












                  2








                  2





                  $begingroup$

                  I see two improvement points in the code.



                  1. It is better to use getLine() and store the input in char* instead of reading each char and appending to a stack

                  2. It is more than enough to iterate till half of the string as the remaining half is checked in the first half iteration cstack.top() != cqueue.front()





                  share|improve this answer









                  $endgroup$



                  I see two improvement points in the code.



                  1. It is better to use getLine() and store the input in char* instead of reading each char and appending to a stack

                  2. It is more than enough to iterate till half of the string as the remaining half is checked in the first half iteration cstack.top() != cqueue.front()






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 8 hours ago









                  Ramanathan GanesanRamanathan Ganesan

                  4394 silver badges5 bronze badges




                  4394 silver badges5 bronze badges




















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









                      draft saved

                      draft discarded


















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












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











                      Avantika P 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%2f223680%2fperformance-issue-in-code-for-reading-line-and-testing-for-palindrome%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. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу