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:
- couple
- create a new pair.
- couple
pair<int, string> p1; // 默认构造函数,int和string类型
p1 = make_pair(10, "hello"); // 使用make_pair函数创建pair对象
pair<int, string> p2(20, "world"); // 使用花括号初始化器创建pair对象
- two of something
- Initially
- the next one
- couple
int val1 = p1.first; // 获取pair的第一个元素
string val2 = p1.second; // 获取pair的第二个元素
- two items that are matched or meant to be used together
- couple
p1.first = 30; // 修改pair的第一个元素
p1.second = "world"; // 修改pair的第二个元素
- couple
- two items that go together
- couple
bool result = (p1 < p2); // 判断p1是否小于p2,按照字典顺序判断
- couple
- a couple
- vector – an array or list of elements designed to represent direction and magnitude in mathematical or physical contexts
- 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.