The syntax for inserting strings into a list, maintaining alpha order.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #1

    The syntax for inserting strings into a list, maintaining alpha order.

    Could someone please explain why the first code snippet inserts properly into a list and the second code snippet does not. The position of the bold expressions are the only differences. iter, s and LS were declared elsewhere in main().
    snippet 1.)
    Code:
    while (true) {
        cout << "Enter string (ENTER to exit): ";
        getline(cin, s);
        if (s.size() == 0)
               break;
        for(iter=LS.begin();iter != LS.end() && s > *iter; )
           [B]iter++;[/B]
           LS.insert(iter, s);
        }
    snippet 2.)
    Code:
    while (true) {
              cout << "Enter string (ENTER to exit): ";
              getline(cin, s);
              if (s.size() == 0)
                   break;
              //LS.push_back(s);
         for(iter=LS.begin();iter != LS.end() && s > *iter;   [B]iter++[/B])
              
              LS.insert(iter, s);
        }
    thanks in advance.
  • johny10151981
    Top Contributor
    • Jan 2010
    • 1059

    #2
    The difference between two code can be described as below:
    Code 1 for loop in little detail:
    Code:
    for(iter=LS.begin();iter != LS.end() && s > *iter; )
    {
           iter++;
    }
    LS.insert(iter, s); //this line is out of for loop
    Code 2 for loop in little detial:
    Code:
    for(iter=LS.begin();iter != LS.end() && s > *iter;   iter++)
    {
       LS.insert(iter, s); //this line is in for loop, but in the above code, it is out of for loop
    }
    the equivalent code for the first for loop is

    Code:
    for(iter=LS.begin();iter != LS.end() && s > *iter;        iter++);//the semicolon at the end

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      This is a good example to why it's a good habit to use braces rather than rely on semi-colons.

      Comment

      Working...