How to use the move_backward function to move a range of elements to a new location in backwards order in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

// Function to shift the first 3 elements of a vector to the right-most positions
void shift_elements_right(std::vector<std::string>& data) {
    if (data.size() < 3) {
        return;
    }

    // Define the source range: the first 3 elements [begin, begin + 3)
    auto first = data.begin();
    auto last = data.begin() + 3;

    // Define the destination past-the-end iterator (the end of the vector)
    auto destination_end = data.end();

    // Perform the backward move to prevent overwriting source data during the right-shift
    
    // The algorithm returns a ranges::move_backward_result struct 
    // containing 'in' and 'out' iterators.
    auto result = std::ranges::move_backward(first, last, destination_end);

    // Optional: You can inspect result.out, which points to the first 
    // element of the newly moved destination range.
    std::cout << "Move completed successfully. Last destination element reached.\n";
}

int main() {
    // Initialize a vector with sample strings
    std::vector<std::string> items = {"Task1", "Task2", "Task3", 
                                      "Placeholder1", "Placeholder2", "Placeholder3"};

    std::cout << "Before shift: ";
    for (const auto& item : items) {
        std::cout << item << " ";
    }
    std::cout << "\n";

    // Execute the shift
    shift_elements_right(items);

    std::cout << "After shift:  ";
    for (const auto& item : items) {
        if (item.empty()) std::cout << "*";
        std::cout << item << " ";
    }
}


/*
run:

Before shift: Task1 Task2 Task3 Placeholder1 Placeholder2 Placeholder3 
Move completed successfully. Last destination element reached.
After shift:  * * * Task1 Task2 Task3 

*/

 



answered Oct 28 by avibootz
...