📜  如何在 C++ 中循环一组对(1)

📅  最后修改于: 2023-12-03 15:24:08.255000             🧑  作者: Mango

如何在 C++ 中循环一组对

对于一组对(pair),可以使用STL提供的容器类来存储和操作。常用的容器类有vector、list、map等。在对一组对进行循环时,可以使用迭代器来进行遍历。

以下示例演示了如何使用vector容器存储一组对,并使用迭代器进行循环遍历:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<pair<int, int>> pairs = {{1, 2}, {3, 4}, {5, 6}};

    for (auto it = pairs.begin(); it != pairs.end(); ++it)
    {
        cout << "Pair: (" << it->first << ", " << it->second << ")" << endl;
    }

    return 0;
}

输出结果如下:

Pair: (1, 2)
Pair: (3, 4)
Pair: (5, 6)

其中,auto关键字可自动推导出迭代器的类型。使用迭代器的箭头运算符可以访问pair中的元素。

除了使用迭代器遍历一组对,也可以使用C++11中新增的范围for语句来进行遍历,示例如下:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    vector<pair<int, int>> pairs = {{1, 2}, {3, 4}, {5, 6}};

    for (auto& p: pairs)
    {
        cout << "Pair: (" << p.first << ", " << p.second << ")" << endl;
    }

    return 0;
}

输出结果与前一个示例相同。

在代码中,auto&表示使用引用类型,可以避免复制vector中的pair对象,提高效率。

除了vector,其他容器类也可以使用类似的方式遍历一组对。