title: Trouble in sorting vector strings using std::sort() using custom compare function
body: <p>I am trying to sort strings according to a rule. The c++ code works in most cases but in some cases gives an error:</p>
  <pre><code>  terminate called after throwing an instance of 'std::logic_error'
    what():  basic_string::_M_construct null not valid
  </code></pre>
  <p>I have seen this error before, it happens when we try to initialize a string as null pointer or 0 (which is internally converted as a null pointer). I have checked that error is happening during sorting and only when I use the custom function for comparison. Once again, I don't know why it is happening only in certain cases.</p>
  <p>The code is:</p>
  <pre><code>#include &lt;algorithm&gt;
  #include &lt;sstream&gt;
  #include &lt;iostream&gt;
  #include &lt;vector&gt;
  #include &lt;string&gt;
  
  using std::vector;
  using std::string;
  
  bool greater(string a, string b) {
    int i = 0;
    a = a + a[0];
    b = b + b[0];
    while(i&lt;a.size() &amp;&amp; i&lt;b.size()) {
      if(a[i] != b[i]) {
        if(a[i] - '0' &gt; b[i] - '0')
        return true;
        else return false;
      }
      i++;
    }
    
  }
  
  string largest_number(vector&lt;string&gt; a) {
    std::sort(a.begin(), a.end(), greater);
    std::stringstream ret;
    for (size_t i = 0; i &lt; a.size(); i++) {
      ret &lt;&lt; a[i];
    }
    string result;
    ret &gt;&gt; result;
    return result;
  }
  
  int main() {
    int n;
    std::cin &gt;&gt; n;
    vector&lt;string&gt; a(n);
    for (size_t i = 0; i &lt; a.size(); i++) {
      std::cin &gt;&gt; a[i];
    }
    std::cout &lt;&lt; largest_number(a);
    return 0;
  }
  </code></pre>
  <p>One of the cases where it gives error is:</p>
  <pre><code>100  
  2 8 2 3 6 4 1 1 10 6 3 3 6 1 3 8 4 6 1 10 8 4 10 4 1 3 2 3 2 6 1 5 2 9 8 5 10 8 7 9 6 4 2 6 3 8 8 9 8 2 9 10 3 10 7 5 7 1 7 5 1 4 7 6 1 10 5 4 8 4 2 7 8 1 1 7 4 1 1 9 8 6 5 9 9 3 7 6 3 10 8 10 7 2 5 1 1 9 9 5
  </code></pre>
  <p>SOLUTION:
  Thanks for help. The error was occurring as the compare function was not returning anything once it goes out of the loop. Here is the updated function that works.</p>
  <pre><code>bool greater(string a, string b) {
    int i = 0;
    a = a + a[0];
    b = b + b[0];
    while(i&lt;a.size() &amp;&amp; i&lt;b.size()) {
        if(a[i] &gt; b[i])
          return true;
      i++;
    }
    return false; 
  }
  </code></pre>