How to use the ranges::mismatch function to find the first position where two ranges differ in C++

1 Answer

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

// Define a simple transaction struct
struct Transaction {
    int id;
    double amount;
};

// Function to find and report the first discrepancy between two transaction logs
void compare_transaction_logs(const std::vector<Transaction>& log_a, 
                                const std::vector<Transaction>& log_b) {
    
    // Use std::ranges::mismatch with projections to compare only the 'id' field of both logs.
    // The syntax is: mismatch(range1, range2, pred, proj1, proj2)
    // '{}' uses the default comparator (std::ranges::equal_to).
    auto result = std::ranges::mismatch(log_a, log_b, {}, &Transaction::id, &Transaction::id);

    // result.in1 points to log_a's mismatch point; result.in2 points to log_b's mismatch point.
    bool reached_end_a = (result.in1 == log_a.end());
    bool reached_end_b = (result.in2 == log_b.end());

    if (reached_end_a && reached_end_b) {
        std::cout << "Both transaction logs are completely identical.\n";
        return;
    }

    std::cout << "First mismatch found:\n";

    if (!reached_end_a) {
        std::cout << "  Log A -> ID: " << result.in1->id 
                  << ", Amount: $" << result.in1->amount << "\n";
    } else {
        std::cout << "  Log A reached the end.\n";
    }

    if (!reached_end_b) {
        std::cout << "  Log B -> ID: " << result.in2->id 
                  << ", Amount: $" << result.in2->amount << "\n";
    } else {
        std::cout << "  Log B reached the end.\n";
    }
}

int main() {
    // Initialize two vectors of transactions
    std::vector<Transaction> audit_log_1 = {
        {101, 50.0},
        {102, 150.0},
        {103, 200.0}
    };

    std::vector<Transaction> audit_log_2 = {
        {101, 50.0},
        {104, 150.0}, // Mismatching ID here
        {103, 200.0}
    };

    compare_transaction_logs(audit_log_1, audit_log_2);
}


/*
run:

First mismatch found:
  Log A -> ID: 102, Amount: $150
  Log B -> ID: 104, Amount: $150

*/

 



answered Oct 28 by avibootz
...