Self implementation of std::next_permutation(), just want to check something

I wrote my own version of next_permutation() and it works fine, but am I missing something?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
bool next_permutation(vector<int>& vec)
{ 
  for(vector<int>::iterator it = vec.end(); it != vec.begin(); it--)
  {
  
    if(*(it - 1) < *(it))
    { 
      for(vector<int>::iterator min = vec.end(); min != it-1; min--)
      {
        if(*min > *(it - 1))
        {
          swap(*(it-1), *min);
          break;
        }
      }
        
      reverse(it, vec.end());
      
      return true;
    }   
    
  }
  
  return false;
}


The output works fine when using this loop:

1
2
3
4
5
6
7
8
  do
  {
    for(vector<int>::iterator it = vec.begin(); it != vec.end(); it++)
      cout << *it << " ";
    
    cout << endl;
  
  } while(next_permutation(vec));


even when I comment out the return false; line, which makes me think the compiler is adding something.

The idea is that the function should return false if the given string/vector is already the last permutation, but true if a new one is generated.

What I have seems fine to me, but the fact that it still works with a crucial line removed worries me. Is it just the compiler adding return false at the end of the function for me that is creating this result?

Thanks!
Doesn't the compiler warn that not all control statements return a value ? Just set a breakpoint on return false; to test that your code reaches that line when it's supposed to.
Last edited on
Nope, no complaints from the compiler.

Instead of setting a breakpoint (because I don't know how) I just added an output line and got the expected result, thanks for the help.
Topic archived. No new replies allowed.