Delete the node at index i from its current position and insert it after node at index j

I was trying to create a function to delete the node at index i from its current position and insert it after node at index j from a std::vector<Node> nodes. These container is logically a circular container of nodes, that is there's no actual first or last node, i.e. after nodes.back() comes nodes[0].

I really need this function not to have bugs and to be as performant as possible, so I'm asking here your help to a further check and for eventual suggestions to improve its performance.

So, this is the function:

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
 * Delete the node at index i from its current position
 * and insert it after node at index j.
 * */
void SimpleSolution::shift(const unsigned i, const unsigned j) {

    assert_not_out_of_bounds({i, j});

    if (j < i) { // ranges [i, end] and [start, j]

        for (unsigned x = i; x < nodes.size() - 1; ++x) {
            std::swap(nodes[x], nodes[x + 1]);
        }

        std::swap(nodes[0], nodes.back());

        for (unsigned x = 0; x < j; ++x) {
            std::swap(nodes[x], nodes[x + 1]);
        }

    } else { // range [i, j]

        if (i != j) {

            for (unsigned x = i; x < j; ++x) {
                std::swap(nodes[x], nodes[x + 1]);
            }

        } else { // i == j

            // i and j are the last elements
            if (i == (nodes.size() - 1)) {
                std::swap(nodes[0], nodes.back());
            } else { // equivalent to std::swap(nodes[i], nodes[i + 1])
                std::swap(nodes[i], nodes[j + 1]);
            }
        }

    }

}


I'm not looking for "idiomatic" C++, but for correctness and performance, but if idiomatic also means correctness and performance, then perfect.
Last edited on
Topic archived. No new replies allowed.