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.
/*
* Delete the node at index i from its current position
* and insert it after node at index j.
* */
void SimpleSolution::shift(constunsigned i, constunsigned 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.