Блог пользователя CLICKHERE

Автор CLICKHERE, 4 года назад, По-английски
#include <bits/stdc++.h>
using namespace std;

class a{
	public:
	vector<int> v;
	a(){
		v = {1,2,3};
	}
	bool cmp(const int &a, const int &b){
		return (a < b);
	}
	void fun(){
		sort(v.begin(), v.end(), cmp);
		for(auto x :v ) {
			cout << x;
		}
	}
};

int main() {
	a b;
	b.fun();
}

why it is giving error at sort(v.begin(), v.end(), cmp); ?

  • Проголосовать: нравится
  • +9
  • Проголосовать: не нравится

»
4 года назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

Did you try looking up your error?

Here's one of the results: http://www.programmersought.com/article/5922553195/

  • »
    »
    4 года назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится
    static bool cmp(const int &a, const int &b){
    		return (a < b);
    	}
    

    like this?

    • »
      »
      »
      4 года назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      You tell me, does it work?

      • »
        »
        »
        »
        4 года назад, # ^ |
          Проголосовать: нравится 0 Проголосовать: не нравится

        But why static?

        • »
          »
          »
          »
          »
          4 года назад, # ^ |
          Rev. 2   Проголосовать: нравится +10 Проголосовать: не нравится

          I think the reason is object-oriented programming stuff. Like sort is outside the class a, so it needs an instance of a to call its cmp function, but sort won't use an instance of a so it just can't call the function.

          But with a static function, apparently just being called inside a member function of a is enough for sort to use the function.

        • »
          »
          »
          »
          »
          4 года назад, # ^ |
          Rev. 2   Проголосовать: нравится +6 Проголосовать: не нравится

          All non-static member methods of class has implicit argument $$$*this$$$, so cmp's full signature is $$$(a*, const int&, const int&)$$$, which is not what sort requires