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);
}

猜你喜欢

转载自blog.csdn.net/a1368783069/article/details/80223126