Toán tin vuotlen.com

Pair trong C++

std::pair trong C++ là một cấu trúc dữ liệu đơn giản nhưng rất hữu ích để lưu trữ hai giá trị liên quan với nhau. Mặc dù std::pair không có nhiều phương thức như các container khác, nhưng nó vẫn có một số phương thức và chức năng cơ bản. Dưới đây là các phương thức và thao tác cơ bản mà bạn có thể sử dụng với std::pair:

Các thành viên dữ liệu của std::pair

Ví dụ:

#include <iostream>
#include <utility>
#include <string>

using namespace std;

int main() {
    // Default constructor
    pair<int, string> p1;
    p1.first = 1;
    p1.second = "One";

    // Parameterized constructor
    pair<int, string> p2(2, "Two");

    // Copy constructor
    pair<int, string> p3(p2);

    // Assignment operator
    pair<int, string> p4;
    p4 = p2;

    // make_pair function
    auto p5 = make_pair(3, "Three");

    // Comparison operators
    pair<int, string> p6(4, "Four");
    pair<int, string> p7(4, "Four");

    if (p6 == p7) {
        cout << "p6 is equal to p7" << endl;
    }

    if (p2 < p5) {
        cout << "p2 is less than p5" << endl;
    }

    // Display pairs
    cout << "Pair p1: (" << p1.first << ", " << p1.second << ")" << endl;
    cout << "Pair p2: (" << p2.first << ", " << p2.second << ")" << endl;
    cout << "Pair p3: (" << p3.first << ", " << p3.second << ")" << endl;
    cout << "Pair p4: (" << p4.first << ", " << p4.second << ")" << endl;
    cout << "Pair p5: (" << p5.first << ", " << p5.second << ")" << endl;
    cout << "Pair p6: (" << p6.first << ", " << p6.second << ")" << endl;
    cout << "Pair p7: (" << p7.first << ", " << p7.second << ")" << endl;

    return 0;
}