STL でベクトルを使ったペアの実装

C++Beginner
オンラインで実践に進む

はじめに

このチュートリアルでは、STL ライブラリの Vector を使って C++ で Pair テンプレートを実装する方法を学びます。具体的には、以下のことを説明します。

ベクトルを宣言して整数のペアで埋める

C++ で Pair テンプレートを実装する最初のステップは、ペアの空のベクトルを宣言してその中に整数のペアを挿入することです。

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

using namespace std;

int main()
{
    //create an empty vector of pair
    vector<pair<int, int>> v;

    //insert elements into the vector
    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;
}

ペアのベクトルを表示する

次に、ペアのベクトルをコンソールに表示します。firstsecond 属性を使ってペア要素にアクセスできます。

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; //accessing the pair elements
}

ベクトルを昇順にソートする

最後に、STL ライブラリの sort 関数を使ってベクトルを昇順にソートします。デフォルトでは、ペアの最初の要素を基準にソートされます。

//Sorting the vector in ascending order - by default on the basis of first element of the pair
sort(v.begin(), v.end());

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

//prining the Sorted vector
for (int i = 0; i < n; i++)
{
    cout << "\nSquare of " << v[i].first << " is " << v[i].second; // accessing the pair elements
}

まとめ

このチュートリアルでは、C++ で STL の Vectors を使って Pairs を実装する方法を学びました。ペアの空のベクトルを宣言し、整数のペアで埋め、ペアのベクトルを表示し、ベクトルを昇順にソートする方法について説明しました。上記のコード例に従うことで、Pair テンプレートを使って C++ コードをより効率的で有効にすることができます。