stl 的utility

本文详细介绍了C++中pair类的使用方法,包括如何创建pair对象、如何为pair对象赋值,以及如何使用make_pair函数。此外,还展示了如何通过重载运算符来比较pair对象,并给出了一些具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

std::pair

#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;
}
utility重载了operators ==<!=>>= and <=, 这样pair 对象也可以比较了,不过先比较第一个元素 ,只有第一个元素相等的情况下才比较第2个
utility 里面的make_pair
pair <int,int> one;
  pair <int,int> two;
  one = make_pair (10,20);
  two = make_pair (10.5,'A'); // ok: implicit conversion from pair<double,char>
  cout << "one: " << one.first << ", " << one.second << "\n";
  cout << "two: " << two.first << ", " << two.second << "\n";
  return 0;
c++ makepair 的的定义
template <class T1,class T2>
  pair<T1,T2> make_pair (T1 x, T2 y)
  {
    return ( pair<T1,T2>(x,y) );
  }

std::rel_ops

namespace rel_ops {
  template <class T> bool operator!= (const T& x, const T& y) { return !(x==y); }
  template <class T> bool operator>  (const T& x, const T& y) { return y<x; }
  template <class T> bool operator<= (const T& x, const T& y) { return !(y<x); }
  template <class T> bool operator>= (const T& x, const T& y) { return !(x<y); }
}
如果使用了utility ,一个类只定义 < 和==, 其他操作符 >,<=,>=就会根据< ,自动生成代码, != 会根据== 生成代码,
例子如下
// rel_ops example:
#include <iostream>
#include <utility>
#include <cmath>
using namespace std;

class vector2d {
public:
  double x,y;
  vector2d (double px,double py): x(px), y(py) {}
  double length () const {return sqrt(x*x+y*y);}
  bool operator==(const vector2d& rhs) const {return length()==rhs.length();}
  bool operator< (const vector2d& rhs) const {return length()< rhs.length();} 
};

using namespace rel_ops;

int main () {
  vector2d a (10,10);	// length=14.14
  vector2d b (15,5);	// length=15.81
  cout << boolalpha;
  cout << "(a<b) is " << (a<b) << "\n";
  cout << "(a>b) is " << (a>b) << "\n"; // 没有定义> ,操作符,但是有#include <UITILITY> 就行了#include <utility>

return 0;
}
Output:

(a<b) is true
(a>b) is false
 
 
 

转载于:https://www.cnblogs.com/gisbeginner/archive/2012/12/30/2839749.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值