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_pairstd::pair<int, char> my_pair;// Now assign the first element to an integermy_pair.first = 10;// And the second element to a charactermy_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)

  • cppreference.com page on STL PairSTL对上的cppreference.com页面


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

stl标准模板库

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

  1. freemarker中运算符_如何在Web应用系统表示层开发中应用Velocity模板技术

    软件项目实训及课程设计指导--如何在Web应用系统表示层开发实现中应用Velocity模板技术 1.分离Web表示层的数据处理和展现逻辑的常见的应用技术 分离Web表示层的数据处理和展现逻辑是目前企业 ...

  2. vue 修改模板{{}}标签_详解Vue 动态添加模板的几种方法

    以下方法只适用于 Vue1.0 版本,推荐系数由高到低排列. 通常我们会在组件里的 template 属性定义模板,或者是在*.vue文件里的 template 标签里写模板.但是有时候会需要动态生成 ...

  3. 博途数据类型wstring怎么用_如何在STEP 7 (TIA 博途)中使用“用户定义数据类型” (UDTS)...

    说明 创建一个 PLC 数据类型,在项目导航中打开" PLC 数据类型"文件夹并双击"添加新数据类型".新创建的 PLC 数据类型将分配一个默认名称.如果想更改 ...

  4. python dash库_让你事半功倍的小众 Python 库

    WGET 提取数据,特别是从网络中提取数据是数据科学家的重要任务之一.Wget 是一个免费的工具,用于以非交互式方式从 Web 上下载文件.它支持 HTTP.HTTPS 和 FTP 协议,通过 HTT ...

  5. python如何下载os库_简谈下载安装Python第三方库的三种方法

    如何下载安装Python第三方库(注:此文章以Windows的安装环境为前提) 一.利用Python中的pip进行第三方库的下载 首先我们要搞清楚Python中的pip是个什么东东?pip是一个安装和 ...

  6. python翻译库_[译] 鲜为人知的数据科学 Python 库

    Python 是一个很棒的语言.它是世界上发展最快的编程语言之一.它一次又一次地证明了在开发人员职位中和跨行业的数据科学职位中的实用性.整个 Python 及其库的生态系统使它成为全世界用户(初学者和 ...

  7. python 标准模板库_比较了3个Python模板库

    python 标准模板库 在我的日常工作中,我花费大量时间将各种来源的数据整理成人类可读的信息. 虽然在很多时候,这只是以电子表格或某种类型的图表或其他数据可视化的形式出现,但在其他情况下,有意义的是 ...

  8. python mqtt库_如何在 Python 中使用 MQTT

    Python 是一种广泛使用的解释型.高级编程.通用型编程语言.Python 的设计哲学强调代码的可读性和简洁的语法(尤其是使用空格缩进划分代码块,而非使用大括号或者关键词).Python 让开发者能 ...

  9. ubuntu安装zlib库_如何在Ubuntu中安装zlib库?

    ubuntu安装zlib库 On Ubuntu (18.04), installing zlib reported unable to locate package zlib: 在Ubuntu(18. ...

最新文章

  1. Linux内存技术分析(上)
  2. 在Mac上使用pip3安装python的数据统计模块实录
  3. 互联网金融投放获客优化的讨论(新用户引导流程)
  4. ConsurrentDictionary并发字典知多少?
  5. android webview js 交互框架,自定义android混合框架开发实践1:实现基础andorid和webview交互...
  6. 什么是python之禅_【Python面试】你了解什么是 Python 之禅么?
  7. 华为成了!鸿蒙OS 2.0对比iOS 14:苹果流畅度竟完败?
  8. The minimum required Cuda capability is 3.7.
  9. mysql一列数据转为一行_最最完整的 MySQL 规范都在这了
  10. python谱聚类算法_谱聚类 - python挖掘 - 博客园
  11. presto 正则提取函数
  12. ios开发错误之: Undefined symbols for architecture x86_64
  13. vmware 12 可用 序列号
  14. 自定义httpSession
  15. win11系统项目启动报java.lang.IllegalStateException: Unmapped relationship: 7错误的解决
  16. 学习《医学三字经白话解》之咳嗽+疟疾+痢证
  17. mininet-wifi安装openflow13
  18. GIF、SVG、PNG、图片格式转换
  19. 计算机风扇介绍,如何选择计算机风扇?
  20. Android 系统原生TTS使用

热门文章

  1. iOS开发-使用Storyboard进行界面跳转及传值
  2. 面试求职中需要了解的Java多线程知识
  3. POJ - 1008 Maya Calendar
  4. 80后的80条幽默有哲理的语录
  5. Web页面打印及GridView导出到Excel
  6. [转载] c++与python 数据类型对应
  7. [转载] python计时函数timeit.timeit()使用小结
  8. Django之form组件加cookie,session
  9. 在Linux下使用linuxdeployqt发布Qt程序
  10. 顺利通过EMC实验(13)