C++ Vector sort odd and even stay

2019-09-14 06:59发布

问题:

whats wrong about this code? I want to sort odd numbers but even stay int their places, made function for this but compilator wont pass this

There is error:

error: reference to non-static member function must be called

and there is a code:

public:
std::vector<int> sortArray(std::vector<int> array)
{
   std::vector<int> sortedArray(array);
   std::sort ( sortedArray.begin() , sortedArray.end() , oddSort );
}

bool oddSort ( const int& left , const int& right ){
  if ( left % 2 && right % 2 )
    return left < right;
  else if ( left % 2 )
    return false;
  else if ( right % 2 )
    return true;
  return left < right;
}

回答1:

Danh's comment is right, but this is actually a duplicate question. However, there are no duplicates with accepted answers yet.

So: the problem is that member functions need a this pointer, unless they're static. And std::sort won't give you a this pointer, nor do you need one. So making it static is the straightforward solution.



回答2:

sort is not a method of the class so it will not have the correct this pointer, so calling a member function is a problem.

When a non-static class member is used in any of the contexts where the this keyword is allowed (non-static member function bodies, member initializer lists, default member initializers), the implicit this-> is automatically added before the name, resulting in a member access expression (which, if the member is a virtual member function, results in a virtual function call).

http://en.cppreference.com/w/cpp/language/this



回答3:

I would suggest you have a look at this. There is a difference between types of non-static member function and static member function. And I believe the cpp concept Compare requires the form like the static ones