stl标准模板库_如何在C ++ STL(标准模板库)中使用Pair

stl标准模板库

In this article, we’ll take a look at using pair in C++ Standard Template Library (STL).

在本文中,我们将研究在C ++标准模板库( STL )中使用

This is quite a useful container, which serves to reduce the pain of working with a single return type.

这是一个非常有用的容器,可减轻使用单个返回类型的麻烦。

Similar to a tuple in Python, the std::pair template class is the C++ way of having multiple objects in one variable.

与Python中的元组类似, std::pair模板类是在一个变量中具有多个对象的C ++方法。

Let’s look at how we can use this, use some illustrative examples!

让我们看看如何使用它,使用一些说明性示例!



std :: pair的基本语法 (Basic Syntax of std::pair)

This is in the std namespace, so we need to prefix the namespace name before using it.

这在std名称空间中,因此我们需要在使用名称空间名称之前添加前缀。

This is a template class, and can take templated arguments, based on the type.

这是一个模板类,并且可以根据类型采用模板化参数。


template <class T1, class T2> struct pair;

To declare a pair variable called my_pair, the syntax is as follows:

要声明一个名为my_pair的对变量,语法如下:


std::pair<typename T1, typename T2> my_pair;

Here, T1 and T2 can be of any type, such as int, char, string, etc.

在这里, T1T2可以是任何类型,例如intcharstring等。

Now that we have our pair variable declared, let’s now define it.

现在已经声明了pair变量,现在让我们对其进行定义。

A pair has two elements, called first and second.

一对具有两个元素,分别称为firstsecond

  • To get/set the first element, use my_pair.first.

    要获取/设置第一个元素,请使用my_pair.first
  • To get/set the second element, use my_pair.second.

    要获取/设置第二个元素,请使用my_pair.second

The elements must be of the appropriate type which conforms to T1 and T2, in the declaration.

元素必须是符合声明中T1T2的适当类型。

Let’s now assign the pair elements to specific values.

现在让我们将对元素分配给特定值。

We’ll construct a pair of std::pair<int, char>, and assign it to 2 values accordingly.

我们将构造一对std::pair<int, char> ,并相应地将其分配给2个值。


#include <iostream>

int main() {

    // Define my_pair
    std::pair<int, char> my_pair;

    // Now assign the first element to an integer
    my_pair.first = 10;

    // And the second element to a character
    my_pair.second = 'H';

    std::cout << "First element : " << my_pair.first << std::endl;
    std::cout << "Second element : " << my_pair.second << std::endl;
    return 0;
}

Output

输出量


First element : 10
Second element : H

As you can observe, we can easily manipulate the pair elements!

如您所见,我们可以轻松地操纵pair元素!



在C ++ STL中初始化配对 (Initializing a Pair in C++ STL)

We can also directly initialize a pair variable, using it’s constructor!

我们还可以使用其构造函数直接初始化一个对变量!

Look at the below example, which directly constructs a pair.

看下面的例子,它直接构造了一对。

Here, I have used the auto keyword, which is very useful for automatic type inference!

在这里,我使用了auto关键字,这对于自动类型推断非常有用!

We don’t need to write the huge std::pair<> again and again!

我们不需要一次又一次地编写巨大的std::pair<>


#include <iostream>
#include <string>

int main() {
    // Initialize a pair directly!
    auto my_pair = std::pair<int, std::string>(1, "Hello");

    std::cout << "First element : " << my_pair.first << std::endl;
    std::cout << "Second element : " << my_pair.second << std::endl;
    return 0;
}

Output

输出量


First element : 1
Second element : Hello

Indeed, we were able to directly initialize the pair variable.

确实,我们能够直接初始化对变量。

使用std :: make_pair()进行简洁的初始化 (Concise initialization using std::make_pair())

Another way of initializing a pair is to use the std::make_pair(T1 a, T2 b) function.

初始化对的另一种方法是使用std::make_pair(T1 a, T2 b)函数。

The advantage to this way is that we do have not to explicitly have to specify the types!

这种方式的优点是我们不必显式地指定类型!

This makes writing short and concise code more easier! Look at the same example above, now rewritten using std::make_pair().

这使得编写简短的代码更加容易! 看上面的相同示例,现在使用std::make_pair()重写。


#include <iostream>
#include <string>

int main() {
    auto my_pair = std::make_pair(1, "Hello");

    std::cout << "First element : " << my_pair.first << std::endl;
    std::cout << "Second element : " << my_pair.second << std::endl;
    return 0;
}

I never once mentioned the type name here. auto and make_pair() did this work for us!

我从来没有在这里提到类型名称。 automake_pair()为我们完成了这项工作!


First element : 1
Second element : Hello

Let’s now look at some other things that we can do with this container class!

现在让我们看一下此容器类可以做的其他事情!

std :: pair的默认运算符 (Default Operators for std::pair)

We’ll look at how we can compare two std::pair variables using logical operators.

我们将研究如何使用逻辑运算符比较两个std::pair变量。

  • If we want to assign a pair to another pair variable, using =, the first value of the first pair is assigned to the first value of the second pair. (Same for second element)

    如果我们要使用=将一对分配给另一个对变量,则将第一对的第一个值分配给第二对的第一个值。 (与第二个元素相同)
  • The != operator compares the first and second elements, and returns True only if any one of them are not equal.

    !=运算符比较第一个和第二个元素,并且仅当其中任何一个不相等时才返回True。
  • Similarly, the == operator also does a corresponding comparison.

    同样, ==运算符也进行相应的比较。
  • The <= and >= operators first check the first two elements of both pairs, and return the comparison. If they are equal, the second elements are compared.

    <=>=运算符首先检查两个对的前两个元素,然后返回比较。 如果它们相等,则比较第二个元素。

To illustrate all these operators, a simple example may be easy to visualize.

为了说明所有这些运算符,一个简单的示例可能很容易可视化。


#include <iostream> 
  
int main() 
{ 
    std::pair<int, int>pair1 = make_pair(10, 12); 
    std::pair<int, int>pair2 = make_pair(10, 14); 
  
    std::cout << (pair1 == pair2) << std::endl; 
    std::cout << (pair1 != pair2) << std::endl; 
    std::cout << (pair1 >= pair2) << std::endl; 
    std::cout << (pair1 <= pair2) << std::endl; 
  
    return 0; 
} 

Output

输出量


0
1
0
1

使用std :: pair重载运算符 (Operator Overloading with std::pair)

We can overload certain specific operators directly, on std::pair.

我们可以在std::pair上直接重载某些特定的运算符。

The below operators can be overloaded in C++20.

下面的运算符可以在C ++ 20中重载。

  • Operator ==

    运算子==
  • Operator <=>

    运算符<=>

PLEASE NOTE: All the logical operators except == CANNOT be overloaded in C++20. This is a major change as compared to C++17.

请注意C = 20中 不能重载除==之外的所有逻辑运算符。 与C ++ 17相比,这是一个重大更改。

Let’s take an example of overloading the logical equals operator (==).

让我们以重载逻辑等于运算符( == )为例。

We’ll overload this to compare values of a pair. To be equal, both the first and second values must match.

我们将对此重载以比较一对值。 为了相等,第一个和第二个值必须匹配。


template <typename T1, typename T2>
bool operator== (std::pair <T1, T2> &p, std::pair <T1, T2> &q) {
    if (p.first == q.first && p.second == q.second) {
        std::cout << "Equal\n";
        return true;
    }
    std::cout << "Not Equal\n";
    return false;
}

The complete code is shown below:

完整的代码如下所示:


#include <iostream>
#include <string>

template <typename T1, typename T2>
bool operator== (std::pair <T1, T2> &p, std::pair <T1, T2> &q) {
    if (p.first == q.first && p.second == q.second) {
        std::cout << "Equal\n";
        return true;
    }
    std::cout << "Not Equal\n";
    return false;
}

int main() {
    auto p = std::make_pair(1, "Hello");
    auto q = std::make_pair(1, "Hello");

    if (p == q) {
        printf("True\n");
    }
    else {
        printf("False\n");
    }

    auto r = std::make_pair(1, "Hello");
    auto s = std::make_pair(1, "JournalDev");

    if (r == s) {
        printf("True\n");
    }
    else {
        printf("False\n");
    }
    return 0;
}

Output

输出量


Equal
True
Not Equal
False

As you can see, we have indeed overloaded the == operator to make this work for std::pair as well!

如您所见,我们确实已经重载了==运算符,以使其也可以用于std::pair



结论 (Conclusion)

In this article, we learned how we could use the pair container class in C++ STL. We also saw how we could use different operators on two sets of pairs.

在本文中,我们学习了如何在C ++ STL中使用配对容器类。 我们还看到了如何在两组对上使用不同的运算符。

参考资料 (References)



翻译自: https://www.journaldev.com/39642/pair-in-c-plus-plus-stl

stl标准模板库

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值