使用 Vector 在 STL 中实现 Pair

C++C++Beginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本教程中,我们将学习如何使用 STL 库中的 Vector 在 C++ 中实现 Pair 模板。具体来说,我们将涵盖以下内容:


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL cpp(("`C++`")) -.-> cpp/BasicsGroup(["`Basics`"]) cpp(("`C++`")) -.-> cpp/ControlFlowGroup(["`Control Flow`"]) cpp(("`C++`")) -.-> cpp/OOPGroup(["`OOP`"]) cpp(("`C++`")) -.-> cpp/IOandFileHandlingGroup(["`I/O and File Handling`"]) cpp(("`C++`")) -.-> cpp/StandardLibraryGroup(["`Standard Library`"]) cpp/BasicsGroup -.-> cpp/data_types("`Data Types`") cpp/ControlFlowGroup -.-> cpp/for_loop("`For Loop`") cpp/OOPGroup -.-> cpp/classes_objects("`Classes/Objects`") cpp/IOandFileHandlingGroup -.-> cpp/output("`Output`") cpp/StandardLibraryGroup -.-> cpp/standard_containers("`Standard Containers`") subgraph Lab Skills cpp/data_types -.-> lab-96151{{"`使用 Vector 在 STL 中实现 Pair`"}} cpp/for_loop -.-> lab-96151{{"`使用 Vector 在 STL 中实现 Pair`"}} cpp/classes_objects -.-> lab-96151{{"`使用 Vector 在 STL 中实现 Pair`"}} cpp/output -.-> lab-96151{{"`使用 Vector 在 STL 中实现 Pair`"}} cpp/standard_containers -.-> lab-96151{{"`使用 Vector 在 STL 中实现 Pair`"}} end

声明一个 Vector 并用整数对填充它

在 C++ 中实现 Pair 模板的第一步是声明一个空的 pair 向量,并向其中插入整数对。

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main()
{
    //创建一个空的 pair 向量
    vector<pair<int, int>> v;

    //向向量中插入元素
    v.push_back(make_pair(8, 64));
    v.push_back(make_pair(1, 1));
    v.push_back(make_pair(3, 6));
    v.push_back(make_pair(2, 4));
    v.push_back(make_pair(5, 25));

    return 0;
}

打印 Pair 向量

接下来,我们将把 pair 向量打印到控制台。我们可以使用 firstsecond 属性访问 pair 中的元素。

cout << "Printing the Vector of Pairs: \n";

int n = v.size();

for (int i = 0; i < n; i++)
{
    cout << "\nSquare of " << v[i].first << " is " << v[i].second; //访问 pair 中的元素
}

按升序排序 Vector

最后,我们将使用 STL 库中的 sort 函数对向量进行升序排序。默认情况下,它会根据 pair 的第一个元素进行排序。

//按升序排序向量 - 默认根据 pair 的第一个元素排序
sort(v.begin(), v.end());

cout << "\n\n\n\nThe elements of the Vector after Sorting are:\n ";

//打印排序后的向量
for (int i = 0; i < n; i++)
{
    cout << "\nSquare of " << v[i].first << " is " << v[i].second; // 访问 pair 中的元素
}

总结

在本教程中,我们学习了如何在 C++ 中使用 STL 的 Vector 实现 Pair。我们涵盖了声明一个空的 pair 向量、用整数对填充它、打印 pair 向量以及按升序排序向量的内容。通过跟随上述代码示例,你可以开始利用 Pair 模板使你的 C++ 代码更加高效和有效。

您可能感兴趣的其他 C++ 教程