声明为pair类型的变量可以有三种赋值方法: 1. 通过初始化赋值 直接声明的时候 后面加括号并且数据,如下a 2. 通过.first .second 来赋值 如下b 3. 通过 = make_pair() 来赋值, 如下c
a. pair <string,double> product1 ("tomatoes",3.25);
pair <string,double> product2;
pair <string,double> product3;
b.product2.first = "lightbulbs"; // type of first is string product2.second = 0.99; // type of second is double
c.product3 = make_pair ("shoes",20.0);
template <class T1, class T2> struct pair;
Pair of values
This class couples together a pair of values, which may be of different types (T1 and
T2). The individual values can be accessed through the public members
first and second.
The class is defined as:
|
|
Members
- first_type, second_type
- Alises of template parameters T1 and T2 respectively.
- first, second
- Data members containing the first and second values stored in the
pair. - pair()
- Constructs a pair object with each of its members first and
second constructed with their respective default constructors. - pair(const T1& x, const T2& y)
- Constructs a pair object with its members first and second initialized to
x and y, respectively. - template <class U, class V> pair (const pair<U,V> &p)
- Constructs a pair object with its members first and second initialized to the corresponding elements in
p, which must be of any couple of implicitly-convertible types (including the same types). -
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream> #include <utility> #include <string> using namespace std; int main () { pair <string,double> product1 ("tomatoes",3.25); pair <string,double> product2; pair <string,double> product3; product2.first = "lightbulbs"; // type of first is string product2.second = 0.99; // type of second is double product3 = make_pair ("shoes",20.0); cout << "The price of " << product1.first << " is $" << product1.second << "\n"; cout << "The price of " << product2.first << " is $" << product2.second << "\n"; cout << "The price of " << product3.first << " is $" << product3.second << "\n"; return 0; }
Output:
The price of tomatoes is $3.25 The price of lightbulbs is $0.99 The price of shoes is $20
原文链接: https://www.cnblogs.com/nealgavin/archive/2012/11/29/3205991.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/70992
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!