Pair - Store Two Values Together

Pair - Store Two Values Together

Medium C++ STL 40 views
Explanation Complexity

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.

Example

x = 10
y = 20
First value  = 10
Second value = 20

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 Explanation

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.

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 Explanation

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.

Input / Output Format

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

Examples

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

Example Solution (Public)

C++
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;
    }
}

Official Solution Code

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;
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.