I have got this class:

class sample{
	private:
		int number;
		string adress;
	public:
		int get_number();
		string get_adress();
		sample();
		~sample();
	};

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?

Recommended Answers

All 5 Replies

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::cout<<'\n';

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

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

Sry but is it easy for you to make that example for my case up there?

>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,
Jas.

EDIT: However if you are still really, really desperately stuck, take a look at this thread:
http://www.daniweb.com/forums/thread242984.html
Should clear things up for you somewhat!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.