C++某些函数的介绍

1 std::pair

std::pair主要的作用是将两个数据组合成一个数据,两个数据可以是同一类型或者不同类型。例如std::pair<int,float> 或者 std::pair<double,double>等。pair实质上是一个结构体,其主要的两个成员变量是first和second,这两个变量可以直接使用。

 #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);
    //the price of tomatoes is $3.25
     cout << "the price of " << product1.first << " is $" << product1.second << "\n";
     //the price of lightbulbs is $0.99
     cout << "the price of " << product2.first << " is $" << product2.second << "\n";
     //he price of shoes is $20
     cout << "the price of " << product3.first << " is $" << product3.second << "\n";
     return 0;
 }

2 哈希容器unordered_map

很久以来,STL中都只提供<map>作为存放对应关系的容器,内部通常用红黑树实现,据说原因是二叉平衡树(如红黑树)的各种操作,插入、删除、查找等,都是稳定的时间复杂度,即O(log n);但是对于hash表来说,由于无法避免re-hash所带来的性能问题,即使大多数情况下hash表的性能非常好,但是re-hash所带来的不稳定性在当时是不能容忍的。
不过由于hash表的性能优势,它的使用面还是很广的,于是第三方的类库基本都提供了支持,比如MSVC中的和Boost中的

include <iostream>
#include <string>
#include <unordered_map>

int main()
{
 std::unordered_map<std::string, int> months;
 months["january"] = 31;
 months["february"] = 28;
 months["march"] = 31;
 months["april"] = 30;
 months["may"] = 31;
 months["june"] = 30;
 months["july"] = 31;
 months["august"] = 31;
 months["september"] = 30;
 months["october"] = 31;
 months["november"] = 30;
 months["december"] = 31;
 std::cout << "september -> " << months["september"] << std::endl;
 std::cout << "april   -> " << months["april"] << std::endl;
 std::cout << "december -> " << months["december"] << std::endl;
 std::cout << "february -> " << months["february"] << std::endl;
 return 0;
}

c++ STL容器总结之:vertor与list的应用

3 operator 与 &operator的区别

一个是引用一个是常规的,就像int n2=2 *p=&n2 *q=n2
*p是通过n2的地址来找到n2的值来赋给*p的,*q是直接获取n2的值,
当后面在设n2=3时,*p的数据会随之改变,而*q不变

下面是一个+号的重载操作:
#include <iostream> 
using namespace std; 

//声明
class Point;
Point operator+(Point &a,Point &b);
//Point &operator+(Point &a,Point &b);

//定义点类
class Point 
{ 
public: 
int x,y; 
Point(){}
Point(int xx,int yy){x=xx;y=yy;}
void print(){ cout<<"("<<x<<","<<y<<")\n"; } 
friend Point operator+(Point &a,Point &b); 
//friend Point &operator+(Point &a,Point &b); 
};

//重载+号操作(返回值)
Point operator+( Point &a,Point &b) 
{ 
Point s(a.x+b.x,a.y+b.y); 
return s; 
}

//重载+号操作(返回址)
/*Point &operator+( Point &a,Point &b) 
{ 
a.x+=b.x;
a.y+=b.y; 
return a; 
}*/

//主函数
void main() 
{ 
Point a(3,2),b(1,5),c; 
c=a+b;
c.print(); 
} 
将注释替换过来,就可以得到&operator+的重载了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值