diff --git a/pennylane_lightning/core/src/simulators/lightning_qubit/StateVectorLQubit.hpp b/pennylane_lightning/core/src/simulators/lightning_qubit/StateVectorLQubit.hpp index 822c4e24bc..7d50682a5e 100644 --- a/pennylane_lightning/core/src/simulators/lightning_qubit/StateVectorLQubit.hpp +++ b/pennylane_lightning/core/src/simulators/lightning_qubit/StateVectorLQubit.hpp @@ -768,13 +768,18 @@ class StateVectorLQubit : public StateVectorBase { std::vector all_wires(total_wire_count); std::iota(all_wires.begin(), all_wires.end(), 0); - std::vector controlled_wires; - std::copy_if(all_wires.begin(), all_wires.end(), - std::back_inserter(controlled_wires), - [&wires](const auto val) { - return std::find(wires.begin(), wires.end(), val) == - wires.end(); - }); + std::vector controlled_wires(total_wire_count); + std::iota(std::begin(controlled_wires), std::end(controlled_wires), 0); + + std::vector reversed_sorted_wires(wires); + std::sort(reversed_sorted_wires.begin(), reversed_sorted_wires.end()); + std::reverse(reversed_sorted_wires.begin(), + reversed_sorted_wires.end()); + for (auto wire : reversed_sorted_wires) { + // Reverse guarantees that we start erasing at the end of the array. + // Maybe this can be optimized. + controlled_wires.erase(controlled_wires.begin() + wire); + } const std::vector controlled_values(controlled_wires.size(), false);