error: invalid initialization of reference of type ‘int&’ from expression of type ‘const int’

背景:

使用c++ algorithm sort 进行全排,编译报错。

例程

#include <iostream>     // std::cout
#include <algorithm>    // std::partial_sort
#include <vector>       // std::vector

using namespace std;

bool cmp (int& i, int& j)
{
   return (i<j);
}

int main () {
  int ints[] = {9,8,7,6,5,4,3,2,1};
  vector<int> vec (ints, ints+9);

 sort(vec.begin(), vec.end(), cmp);

 for(int i=0; i<vec.size(); i++)
   cout << "vec sorted ..." << vec[i] << endl;

 return 0;
}

查错

查看sort的函数使用说明 http://www.cplusplus.com/reference/algorithm/sort/,在 comp 参数的说明,其中:

The function shall not modify any of its arguments.

所以,在以上的 cmp 函数中,变量使用的是引用

解决方法

将cmp函数改成:
1 去掉引用

bool cmp (int i, int j)
{
   return (i<j);
}

或者
2 加 const

bool cmp (const int& i, const int& j)
{
   return (i<j);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值