关于C++中sort函数所使用的cmp函数中的&的疑惑
今天很疑惑,发现关于sort函数中的cmp函数大家有着不同的写法。
比如如下代码,有人是这么写的:
bool cmp(int a, int b){ return a>b; } int a[10]; sort(a,a+10,cmp);
也有人是这么写的:
bool cmp(const int &a, const int &b){ return a>b; } int a[10]; sort(a,a+10,cmp);
我想不对啊,&不是去地址的意思吗?用地址比较不是很奇怪吗?
原来&的功能有两点:1. 取地址 2. 表示一个引用。
同时为什么要用const呢?
后来自己写了几个样例比较了一下,发现第二种方法const int &a是最科学的:
#include<iostream> #include<vector> #include<algorithm> using namespace std; bool cmp1(const int &a,const int &b) { // a=1; The change of a&b is not allowed. // b=1; return a>b; }// Best way. bool cmp2(const int a,const int b) { return a>b; }// ???? Everybody just not use the way like this. bool cmp3(int &a, int &b) { return a>b; }// wrong way, a&b might change in the system, like we could assign 1 to a and b. bool cmp4(int a, int b) { a=1; b=1; return a>b; }// wrong way, a&b won"t change in the cmp; but it may cause problem. int main() { vector<int>v; v.push_back(13); v.push_back(23); v.push_back(3); v.push_back(233); v.push_back(113); v.push_back(1113); sort(v.begin(),v.end(),cmp1); int i=0; for(i=0;i<5; i++) { cout<<v[i]<<endl; } return 0; }
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。