I have got this class:

class sample{
		int number;
		string adress;
		int get_number();
		string get_adress();

I allocate dyanmically memory space like this(cause i need an array of pointers to obects):

sample** samples;

samples=new sample*[20];
for(int i=0;i<20;i++){
	samples[i]=new sample;}

My question is how can i sort this array using std::sort function according their string adress?

Edited by kavourdoukos: n/a

8 Years
Discussion Span
Last Post by JasonHippy

By default std::sort uses an overloaded operator< for the type, but you can pass a predicate to std::sort as the third argument:

#include <algorithm>
#include <cstdlib>
#include <iostream>

bool compare ( int *a, int *b )
  return *a < *b;

int main()
  const int n = 10;

  int **p = new int*[n];

  for ( int i = 0; i < n; i++ )
    p[i] = new int ( rand() % 100 );

  for ( int i = 0; i < n; i++ )
    std::cout<< *p[i] <<' ';

  std::sort ( p, p + n, compare );

  for ( int i = 0; i < n; i++ )
    std::cout<< *p[i] <<' ';

Edited by Narue: n/a


>Sry but is it easy for you to make that example for my case up there?
Yes, it's trivial. That's why I left it for you to do.


Ahhh its ok...I understood how to work with ints but i cant understand how to work with a member of a class.You know i have to sort the array of pointers to class but the criteria for this is a member of the class...Any hint or a wasy to guide me?Thanks in advance!


Well think about it!

Take another look at Narue's example and apply that to your problem...

Narue's example uses ints rather than your 'sample' class, but most of the code reflects what you originally posted.
All she's got in addition is a compare function, a call to std::sort and a bit of code to display the sorted array.

Because Narue's comparing pointers to ints, her comparison function uses int pointers. You want to compare two pointers to 'sample' objects.

You want to sort them by 'adress' (address? or a dress?? heh heh!), which is a std::string.
The 'sample' objects are stored as pointers, so to access the 'adress' property which is private you need to call get_adress() via arrow notation (e.g. ptr->get_adress() )

I don't think I can give you any more help without spoonfeeding you the answer and probably getting told off by Narue in the process!
Which I really don't want! heh heh! ;)

Trust me, the answer is staring right in your face!
Cheers for now,

EDIT: However if you are still really, really desperately stuck, take a look at this thread:
Should clear things up for you somewhat!

Edited by JasonHippy: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.