C++ Code Example: Find Pairs with Target Sum

In this code example, the findPairs function takes a vector arr and an integer target as input and returns a vector of pairs containing the elements that sum up to the target value.

The algorithm uses two nested loops to iterate over all possible pairs of elements. The outer loop selects the first element, and the inner loop iterates over the remaining elements to find a matching pair.

For each pair of elements, the algorithm checks if their sum is equal to the target value. If a pair is found, it is added to the pairs vector using the std::make_pair function.

In the main function, an example input array arr and target value target are defined. The findPairs function is called to find the pairs that sum up to the target value, and the resulting pairs are printed to the console.

Code Example

#include <iostream>
#include <vector>
#include <utility>

std::vector<std::pair<int, int>> findPairs(std::vector<int>& arr, int target) {
    std::vector<std::pair<int, int>> pairs;

    // Iterate over all possible pairs of elements
    for (size_t i = 0; i < arr.size(); i++) {
        for (size_t j = i + 1; j < arr.size(); j++) {
            if (arr[i] + arr[j] == target) {
                pairs.push_back(std::make_pair(arr[i], arr[j]));
            }
        }
    }

    return pairs;
}

int main() {
    std::vector<int> arr = {2, 4, 5, 3, 6, 8};
    int target = 9;
    std::vector<std::pair<int, int>> result = findPairs(arr, target);

    std::cout << "Pairs that sum up to " << target << " are:" << std::endl;
    for (const auto& pair : result) {
        std::cout << "(" << pair.first << ", " << pair.second << ")" << std::endl;
    }

    return 0;
}
Output
Pairs that sum up to 9 are:
(4, 5)
(3, 6)