How to traverse a vector from both sides at the same time in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <utility>   // for std::pair

/*
    Demonstration of traversing a vector from both sides at the same time
    using idiomatic modern C++.

    We use two iterators:
        - 'left'  starts at begin()
        - 'right' starts at end() - 1
    Both move toward the center.

    This approach is efficient (O(n)), avoids index arithmetic,
    and uses the vector's built‑in iterator support.
*/

// ------------------------------------------------------------
// Function: traverse_from_both_sides
// Purpose:  Traverse a vector from both ends simultaneously.
// Returns:  A vector of pairs (left_value, right_value).
// ------------------------------------------------------------
std::vector<std::pair<int,int>>
traverse_from_both_sides(const std::vector<int>& vec) {
    std::vector<std::pair<int,int>> result;

    // Two iterators: one from the left, one from the right
    auto left  = vec.begin();
    auto right = vec.end() - 1;

    // Move inward until they cross
    while (left <= right) {
        result.emplace_back(*left, *right);

        ++left;
        if (right == vec.begin()) break;  // avoid underflow
        --right;
    }

    return result;
}

// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
int main()
{
    std::vector<int> data = {10, 20, 30, 40, 50, 60, 70, 80, 90};

    // Perform the two‑iterator traversal
    auto pairs = traverse_from_both_sides(data);

    // Print results
    std::cout << "Traversing from both sides:\n";
    for (const auto& p : pairs) {
        std::cout << "Left: " << p.first << ", Right: " << p.second << '\n';
    }
}


/*
run:

Traversing from both sides:
Left: 10, Right: 90
Left: 20, Right: 80
Left: 30, Right: 70
Left: 40, Right: 60
Left: 50, Right: 50

*/

 



answered Jul 30 by avibootz
...