ホーム AI・IT [C++] Mastering std::pair: The Basics of Handling Two Values as a Set

[C++] Mastering std::pair: The Basics of Handling Two Values as a Set

真鍋 千夏 真鍋 千夏 • 更新: • 公開: • 読了約 5 分
目次
ne7162ef5c2ec

When writing programs, you frequently encounter situations where you want to treat two values as a pair, such as "key and value," "X and Y coordinates," or "ID and name."

Of course, you could define a struct each time, but there is a much easier way. That is the C++ standard library's std::pair. This is a basic and extremely convenient class specifically designed to handle two values as a single set.

◆ Accessing via first and second Using std::pair is very simple. You declare a variable by specifying the two types you want to pair, like pair<int, string>.

And unlike std::tuple, where you access elements by index number, the contents of a pair are given clear names.

  • .first Accesses the first element.

  • .second Accesses the second element.

Thanks to these intuitive names, first and second, the intent of the code becomes clear. The fact that std::map internally holds key-value pairs as std::pair also utilizes this mechanism.

◆ (C++17 and later) Even more convenient: "Structured Binding" In modern C++, by writing something like auto [id, name] = my_pair;, you can decompose the contents of a pair directly into two independent variables. This makes the code even cleaner and easier to read.

◆ See concrete code and explanations on the blog "I want to see code that actually creates a std::pair and retrieves its values." "What is the convenient helper function make_pair?" "I want to see code using C++17's 'structured binding'."

To answer these questions, on my blog "Mori no Kabu", I explain the basic flow of generating a std::pair and accessing its elements using .first and .second with simple sample code.

▼Click here for detailed sample code and explanations
[C++] How to use std::pair | Handling two values as a pair

Thank you for reading until the end.

同じカテゴリの記事

真鍋 千夏
デジタルマーケター 真鍋 千夏
プロフィールを見る →

美容と暮らしの話題を担当。メーカーの公式発表、商品成分の公表資料、専門家の監修記事をもとに事実を整理します。

おすすめの関連記事