sort using a member of an object in c ++


I'd like to use sort() to do the following

  • I have a text char[] T which is (private) member of a class. The text has length n.
  • I also ave an array int[] P that contains the first n integers.

I'd like to std::sort P such that the lexicographic order among suffixes of T are preserved i.e., for any i < j we have that T[P[i]...n] is lex smaller than T[P[j]...n].

I'm able to do it when char[] T is a global variable by defining

bool myfunction (int i,int j) {
  int m = i, l = j;
  while(m<n and l <n) {
      if(T[m] != T[l]) return (T[m]<T[l]);
      m++; l++;
  return (m<l);

and calling std::sort(P, P+n, myfuction)

I'm in truble when T is a member of an object (and sort is called by a method of that object).

How can I define myfunction so that T is visible? Should it be member of that object? If yes, how? Thank you very much.

Edit: bool instead of int

As you guessed, one way to do it is by defining yourfunction() as a public member of that class.


#include <algorithm>
#include <vector>

using namespace std;

class T
    int value;
        value = rand() % 100;

    static bool Compare(const T &a, const T &b)
        return a.value < b.value;

int main(int argc, char** argv)
    vector<T> data;

    //add some data
    for (int i=0; i<10; i++)

    //sort using static method that can access private attributes
    std::sort(data.begin(), data.end(), T::Compare);