MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

C++ Program to Pair - Store Two Values Together with Explanation

C++ Medium STL 39 views
This problem helps you practice core C++ fundamentals in a practical way. It builds intuition around pair, two, store. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Store two related values as single unit.
Real Life: Storing coordinates (x,y), name-age pairs.

Input Format

No user input.
Two related values are stored together.

Output Format

Both values printed as a single unit.

Constraints

• Use pair

• Values can be of same or different data types

Concept Explanation

Sometimes two values are logically connected and should be stored together.
Example:

• (x, y) coordinates

• (name, age)
C++ provides pair to store two related values as one unit.

Step-by-Step Logic

1.Create a pair variable.

2.Store first value in pair.first.

3.Store second value in pair.second.

4.Both values are now linked together as one unit.

5.Access and print values using .first and .second.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
void stl_q10_pair() { pair<string, int> student = make_pair("Raj", 20); cout << "Name: " << student.first << endl; cout << "Age: " << student.second << endl; // Vector of pairs vector<pair<string, int>> students; students.push_back(make_pair("Priya", 22)); students.push_back(make_pair("Amit", 21)); for(auto s : students) { cout << s.first << " - " << s.second << endl; } }

Output Example

Input:
x = 10 y = 20
Output:
First value = 10 Second value = 20

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next