How is the C++ pair used?

In C++, pair is a template class used for combining two different types of values into a single unit, making it easy to pass, return, or store the two values together.

The use of the word “pair” is as follows:

  1. couple
  2. create a new pair.
  3. couple
pair<int, string> p1; // 默认构造函数,int和string类型
p1 = make_pair(10, "hello"); // 使用make_pair函数创建pair对象
pair<int, string> p2(20, "world"); // 使用花括号初始化器创建pair对象
  1. two of something
  2. Initially
  3. the next one
  4. couple
int val1 = p1.first; // 获取pair的第一个元素
string val2 = p1.second; // 获取pair的第二个元素
  1. two items that are matched or meant to be used together
  2. couple
p1.first = 30; // 修改pair的第一个元素
p1.second = "world"; // 修改pair的第二个元素
  1. couple
  2. two items that go together
  3. couple
bool result = (p1 < p2); // 判断p1是否小于p2,按照字典顺序判断
  1. couple
  2. a couple
  3. vector – an array or list of elements designed to represent direction and magnitude in mathematical or physical contexts
  4. Cartography is the art and science of creating maps.
vector<pair<int, string>> vec; // 使用vector存储多个pair对象
vec.push_back(make_pair(10, "hello")); // 向vector中添加pair对象
pair<int, string> val = vec[0]; // 从vector中获取pair对象

In summary, the use of pairs combines two different types of values together for easy passing, returning, storing, and comparing operations.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds