title: Error "cannot increment value-initialized list iterator" while backtracking
body: <p>I have a list of chars ranging from ['0', '9']. I have to permute over all possible values(10!) for which I have tried to implement backtracking. My logic is to set a char at the current place, remove this char from the list, recurse on the next place and then add this char back again to the same position in the list. The code compiles but gives me a runtime error "Debug assertion failed! Expression: cannot increment value-initialized list iterator".</p>
  
  <p>Here's my code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;list&gt;
  #include &lt;string&gt;
  #include &lt;vector&gt;
  
  using namespace std;
  
  bool isValid(string&amp; s)
  {
      vector&lt;int&gt; V{ 2, 3, 5, 7, 11, 13, 17 };
      for (size_t i = 0; i &lt; V.size(); ++i)
          if (stoi(s.substr(i + 1, 3)) % V[i] != 0)
              return false;
      return true;
  }
  
  long permuteAndFind(list&lt;char&gt; L, string s)
  {
      if (s.size() == 10)
          if (isValid(s))
              return stol(s);
          else
              return 0;
  
      long sum = 0;
      for (list&lt;char&gt;::iterator itr = L.begin(); itr != L.end(); ++itr)
      {
          char c = *itr;
          list&lt;char&gt;::iterator pos = L.erase(itr);
          sum += permuteAndFind(L, s + c);
          L.insert(pos, c);
      }
      return sum;
  }
  
  int main()
  {
      list&lt;char&gt; L{ '0', '1', '2', '3', '4', '5', '6','7', '8', '9' };
      cout &lt;&lt; permuteAndFind(L, "") &lt;&lt; endl;
  }
  </code></pre>
  
  <p>Edit: correct code</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;list&gt;
  #include &lt;string&gt;
  #include &lt;vector&gt;
  
  using namespace std;
  
  bool isValid(string&amp; s)
  {
      vector&lt;int&gt; V{ 2, 3, 5, 7, 11, 13, 17 };
      for (size_t i = 0; i &lt; V.size(); ++i)
          if (stoi(s.substr(i + 1, 3)) % V[i] != 0)
              return false;
      return true;
  }
  
  long permuteAndFind(list&lt;char&gt; L, string s)
  {
      if (s.size() == 10)
          if (isValid(s))
              return stol(s);
          else
              return 0;
  
      long sum = 0;
      for (list&lt;char&gt;::iterator itr = L.begin(); itr != L.end();)
      {
          char c = *itr;
          list&lt;char&gt;::iterator pos = L.erase(itr);
          itr = pos;
          sum += permuteAndFind(L, s + c);
          L.insert(pos, c);
      }
      return sum;
  }
  
  int main()
  {
      list&lt;char&gt; L{ '0', '1', '2', '3', '4', '5', '6','7', '8', '9' };
      cout &lt;&lt; permuteAndFind(L, "") &lt;&lt; endl;
  }
  </code></pre>