stl::pair Example

Example: Using pair to Represent and Manipulate (x, y) Coordinates

Here’s a C++ program that demonstrates how to use pair to store and manipulate (x, y) coordinates.

#include <iostream>
#include <vector>
#include <utility> // For pair
#include <cmath> // For sqrt()

using namespace std;

// Function to calculate the distance between two coordinates
double calculateDistance(pair<int, int> point1, pair<int, int> point2) {
int dx = point2.first - point1.first;
int dy = point2.second - point1.second;
return sqrt(dx * dx + dy * dy);
}

int main() {
// Representing coordinates using pairs
pair<int, int> pointA = {3, 4};
pair<int, int> pointB = {7, 1};

// Displaying the coordinates
cout << "Point A: (" << pointA.first << ", " << pointA.second << ")\n";
cout << "Point B: (" << pointB.first << ", " << pointB.second << ")\n";

// Calculating the distance between two points
double distance = calculateDistance(pointA, pointB);
cout << "Distance between Point A and Point B: " << distance << endl;

// Storing multiple points in a vector of pairs
vector<pair<int, int>> points = {{1, 2}, {3, 4}, {5, 6}};

// Adding a new point
points.push_back({7, 8});

// Displaying all points
cout << "\nAll Points:\n";
for (const auto& point : points) {
cout << "(" << point.first << ", " << point.second << ")\n";
}

// Finding and displaying the midpoint of the first two points
pair<int, int> midpoint = {
(pointA.first + pointB.first) / 2,
(pointA.second + pointB.second) / 2
};
cout << "\nMidpoint of Point A and Point B: (" << midpoint.first << ", " << midpoint.second << ")\n";

return 0;
}

Explanation:

  1. Storing Coordinates:
    • Pairs are used to represent (x, y) coordinates. For example, pointA is {3, 4}.
  2. Manipulating Coordinates:
    • The function calculateDistance computes the Euclidean distance between two points using the formula: distance=sqr((x2−x1)2+(y2−y1)2)
  3. Storing Multiple Points:
    • A vector<pair<int, int>> is used to store multiple (x, y) coordinates.
  4. Finding the Midpoint:
    • The midpoint between two points (x1, y1) and (x2, y2) is: midpoint= ((x1​+x2)/2​​,(y1​+y2)/2​​)

Sample Output:

Point A: (3, 4)
Point B: (7, 1)
Distance between Point A and Point B: 5

All Points:
(1, 2)
(3, 4)
(5, 6)
(7, 8)

Midpoint of Point A and Point B: (5, 2)

This example shows how to use pair to work with simple geometric data in C++.

Scroll to Top