title: why doesn't user defined function sort the elements of same length in the order given?
body: <p>My task is to sort the words of a string in the increasing order of their length and for words of same length, I have to keep them in the order given.
  for ex: &quot;to be or not to be&quot; will become &quot;to be or to be not&quot;.
  i am first making a vector 'v' of all the words in the string and then trying to sort the vector using user defined function in sort() function of C++.
  Here is my code:</p>
  <pre><code>#include &lt;bits/stdc++.h&gt;
  using namespace std;
  static bool comparelength(string first,string second){//function to compare length
      return first.size()&lt;second.size();
  }
  
  int main() {
      string text=&quot;Jlhvvd wfwnphmxoa qcuucx qsvqskq cqwfypww dyphntfz hkbwx xmwohi qvzegb ubogo sbdfmnyeim tuqppyipb llwzeug hrsaebveez aszqnvruhr xqpqd ipwbapd mlghuuwvec xpefyglstj dkvhhgecd kry&quot;;
      vector&lt;string&gt; v;
      string cur=&quot;&quot;;
      text+=&quot; &quot;;
      
  
  for(int i=0;i&lt;text.size();i++){
          if(text[i]==32){//if space is encountered then the word is inserted in the vector
              v.push_back(cur);
              cur=&quot;&quot;;
          }
          else{
              cur+=text[i];//if not space then text[i] is added to the current word
          }
      }
      sort(v.begin(),v.end(),comparelength);//sort the vector
      for(int i=0;i&lt;v.size();i++)
      cout&lt;&lt;v[i]&lt;&lt;&quot; &quot;;
  </code></pre>
  <p>Now it gives this output:
  &quot;Kry xqpqd ubogo hkbwx qvzegb jlhvvd xmwohi qcuucx qsvqskq llwzeug ipwbapd dyphntfz cqwfypww tuqppyipb dkvhhgecd sbdfmnyeim xpefyglstj mlghuuwvec aszqnvruhr hrsaebveez wfwnphmxoa&quot;</p>
  <p>But the correct output should be:
  &quot;Kry hkbwx ubogo xqpqd jlhvvd qcuucx xmwohi qvzegb qsvqskq llwzeug ipwbapd cqwfypww dyphntfz tuqppyipb dkvhhgecd wfwnphmxoa sbdfmnyeim hrsaebveez aszqnvruhr mlghuuwvec xpefyglstj&quot;</p>
  <p>see the position 1,2 and 3(using 0 indexing).</p>
  <p>it should give: hkbwx ubogo xqpqd.</p>
  <p>but it gives:   xqpqd ubogo hkbwx.</p>
  <p>which makes me think that it is not sorting the words of same length in the order given. You can find many other positions where this happens(for ex: 4,5,6 and 7).</p>
  <p>But for the string &quot;leetcode plus try suck geaser is cool best&quot;
  it gives the correct output which is: &quot;is try plus suck cool best geaser
  leetcode&quot;</p>
  <p>Can anyone make it clear why is it not working for the former string but working for the latter.
  I've tried doing</p>
  <pre><code>static bool comparelength(string first,string second){
      if(first.size()==second.size())
      return true;
      if(first.size()&lt;second.size())
      return true;
      else
      return false;
  }
  </code></pre>
  <p>But this throws runtime error.</p>
  <p>sorry for making the question messy but i really want to understand this.</p>