Closest greater lexicographical permutation
Headers and namespaces

We don't use &lt;vector&gt;, but do need &lt;string&gt;.

Bringing all names in from a namespace is problematic; namespace std particularly so.  It can silently change the meaning of your program when you're not expecting it.  Get used to using the namespace prefix (std is intentionally very short), or importing just the names you need into the smallest reasonable scope.

Bug

This loop fails when w is the empty string:

for (auto rit = next(w.rbegin()); rit!=w.rend(); ++rit) {


This can be fixed with an early return:

if (w.empty())
    return w;


Algorithm

There's a standard algorithm called std::next_permutation() that does most of what we need.  The one difference is that if its input is already the last permutation, it will wrap around to the first one and indicate (by its return value) that it has done so. We can use that to return the original input string in that case.

Tests

You've included no tests.  I think we need to test the trivial case (empty string) and at least one case where we must return a new string and one where we already have the last possible permutation.



Improved code

#include &lt;algorithm&gt;
#include &lt;string&gt;

std::string closest_greater_lexicographical_permutation(const std::string&amp; input) {
    auto word = input;
    return std::next_permutation(word.begin(), word.end())
        ? word   // we changed it
        : input; // no change - already the last permutation
}

// Test program

#include &lt;iostream&gt;
static bool test(const std::string&amp; input, const std::string&amp; expected)
{
    auto const actual = closest_greater_lexicographical_permutation(input);
    if (actual == expected)
        return 0;

    std::cerr &lt;&lt; "FAIL (\"" &lt;&lt; input &lt;&lt; "\"): "
        "got \"" &lt;&lt; actual &lt;&lt; "\" "
        "instead of \"" &lt;&lt; expected &lt;&lt; "\"" &lt;&lt; std::endl;
    return 1;
}

int main()
{
    return 0
        + test("", "")
        + test("aabb", "abab")
        + test("cba", "cba")
        ;
}