Please, try EDU on Codeforces! New educational section with videos, subtitles, texts, and problems. ×

CLICKHERE's blog

By CLICKHERE, 5 weeks ago, In English,
#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); ?

 
 
 
 
  • Vote: I like it
  • +9
  • Vote: I do not like it

»
5 weeks ago, # |
  Vote: I like it +1 Vote: I do not like it

Did you try looking up your error?

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

  • »
    »
    5 weeks ago, # ^ |
      Vote: I like it 0 Vote: I do not like it
    static bool cmp(const int &a, const int &b){
    		return (a < b);
    	}
    

    like this?

    • »
      »
      »
      5 weeks ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      You tell me, does it work?

      • »
        »
        »
        »
        5 weeks ago, # ^ |
        Rev. 2   Vote: I like it 0 Vote: I do not like it

        Yes. Perfectly Worked.

      • »
        »
        »
        »
        5 weeks ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        But why static?

        • »
          »
          »
          »
          »
          5 weeks ago, # ^ |
          Rev. 2   Vote: I like it +10 Vote: I do not like it

          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.

        • »
          »
          »
          »
          »
          5 weeks ago, # ^ |
          Rev. 2   Vote: I like it +6 Vote: I do not like it

          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