pair is a template class in the C++ standard library, used to store a combination of two objects

pairIt is a template class in the C++ standard library, used to store a combination of two objects. It is located <utility>in the header file.

pairThe class is defined as follows:

template <class T1, class T2>
struct pair {
    
    
    T1 first;
    T2 second;
  
    pair();
    pair(const T1& x, const T2& y);
    template<class U, class V>
      pair(U&& x, V&& y);
    template<class U, class V>
      pair(const pair<U, V>& p);
    template<class U, class V>
      pair(pair<U, V>&& p) noexcept;
    pair(const pair& p) = default;
    pair(pair&& p) noexcept = default;
}

pairThe class has two public member variables: firstand second, which are used to store two objects respectively. The type of member variables can be any type, including built-in types, custom types, pointer types, etc.

Here is a pairsample code using the class:

#include <iostream>
#include <utility>

int main() {
    
    
    std::pair<std::string, int> myPair("apple", 3);
    
    std::cout << "Fruit: " << myPair.first << std::endl;
    std::cout << "Count: " << myPair.second << std::endl;
    
    return 0;
}

In the above example, we created an pairobject myPairwhere firstthe member is a string "apple" and secondthe member is an integer 3. We then use .the operator to access and output myPairthe object's firstand secondmembers.

Example output:

Fruit: apple
Count: 3

To summarize, paira class is a convenient tool for combining two objects together and can be used in a variety of application scenarios in C++.

Guess you like

Origin blog.csdn.net/m0_46376834/article/details/132761631