目录
pair是一个模板类,可以存储两个值的有序对。通常用于需要返回两个值的函数,或者作为容器(如std::map、std::set)的元素。
pair包含在头文件
template
struct pair {......}
| default (1) | pair(); |
|---|---|
| copy (2) | template |
| initialization (3) | pair (const first_type& a, const second_type& b); |
1.默认构造 pair ()
2.拷贝构造 template
pair (const pair& pr)
3.有参构造 pair (const first_type& a, const second_type& b)
- pair<int, int> pr1;//默认构造
- pair<int, int> pr2(10, 20);//有参构造
- pair<int, int> pr3(pr2);//拷贝构造
| copy (1) | pair& operator= (const pair& pr); |
|---|
1.pair& operator= (const pair& pr)
- pair<int, int> pr1(10, 20);
- pair<int, int> pr2;
- pr2 = pr1;//赋值运算符重载
void swap (pair& pr) noexcept
noexcept关键字是用于指示函数是否抛出异常。如果一个函数使用noexcept关键字声明,并在运行时抛出异常,程序会立即终止。
- pair<int, char> pr1(10, 'a');
- pair<int, char> pr2(20, 'b');
- pr1.swap(pr2);
| (1) | template |
|---|---|
| (2) | template |
| (3) | template |
| (4) | template |
| (5) | template |
| (6) | template |
template
void swap (pair
- pair<int, char> pr1(10, 'a');
- pair<int, char> pr2(20, 'b');
- swap(pr1, pr2);
| lvalue (1) | template |
|---|---|
| rvalue (2) | template |
| const (3) | template |
size_t I 值为0或1,如果I值为0,返回成员first的引用;如果I值为1,返回成员second的引用
- pair<int, char> pr1(10, 'a');
- get<0>(pr1) = 100;//将pr1的第一个成员修改为100
- cout << get<0>(pr1) << endl;//100
template
pair
当需要传入一个pair对象的参数时,使用make_pair会很方便
- void func(pair<int, char> pr)
- {
- cout << pr.first << " " << pr.second << endl;
- }
- void test()
- {
- func(make_pair(10, 'a'));
- }
-
- pair<int, char> pr1;
- pr1 = make_pair(20, 'b');