Using sort() with function

Hello.
This is my sort() function:

 
sort(evens.begin(), evens.end(), second);

...which is using:
 
 bool second(int i, int j) { return (find_prod(i)<find_prod(j)); }

...which is using find_prod() defined by me.
It seems It's working fine. But how do I modify it so that when find_prod(i)==find_prod(j) the first number will be the smaller (i or j without find_prod() function)? Shall I use tie? If so, how?
Last edited on
You have a function:
1
2
3
4
5
6
bool second( int i, int j )
{
  bool result;
  result = find_prod(i) < find_prod(j);
  return result;
}

And you want to change it so that the result of the computation on line 4 will be:
true, IF find_prod(i) < find_prod(j)
false, IF find_prod(i) > find_prod(j)
true, IF find_prod(i) == find_prod(j) AND i < j
false, IF find_prod(i) == find_prod(j) AND !(i < j)

How about some if else?


Note, your functions imply that the find_prod accesses some global variable. The use of global variables is almost always a bad design.
So:
1
2
3
4
5
6
bool second( int i, int j )
{
  if (find_prod(i)!=find_prod(j))
  return find_prod(i) < find_prod(j);
  else return i<j;
}


Note, your functions imply that the find_prod accesses some global variable.


I'm not sure if I understand this. I'm not using global variables.

1
2
3
4
5
6
7
8
9
10
int find_prod(int num)
{
	int prod = 1;
	while (num != 0)
	{
		prod *= num % 10;
		num /= 10;
	}
	return prod;
}
My bad. I (mistakenly) assumed that find_prod does some kind of database lookup.

Anyway. You should not repeat the "expensive" calculations. Cache the results.
1
2
3
4
5
6
bool second( int i, int j )
{
  const auto lhs = find_prod(i);
  const auto rhs = find_prod(j);
  // the comparison logic
}
You mean:
1
2
3
4
5
6
7
8
bool second( int i, int j )
{
  const auto lhs = find_prod(i);
  const auto rhs = find_prod(j);
  if (lhs!=rhs)
  return lhs < rhs;
  else return i<j;
}

Right?
Yes. One could as well write:
1
2
if ( lhs == rhs ) return i < j;
else return lhs < rhs;

or
return ( lhs == rhs ) ? ( i < j ) : ( lhs < rhs );

No real difference.
Thank you.
keskiverto,
Could I do the same with this ( http://www.cplusplus.com/forum/beginner/159720/ )?
Topic archived. No new replies allowed.