Sorting vectors with a compare function.

I can't figure out why the following isn't working:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <algorithm>
#include <vector>

struct turtle {
	turtle(){}
	turtle(Int_t f_i, Double_t t_i) : f(f_i), t(t_i) {}
	Int_t f;
	Double_t t;
	void Show() { cout << f << " " << t << "\n"; }
};

bool compare_turtle_t(turtle& a, turtle& b) {
	return (a.t < b.t);
}

void test() {
	vector<turtle> turtles;
	vector<turtle>::iterator i;
	
	turtle a(1,10);
	turtle b(2,13);
	turtle c(3,8);
	turtle d(4,24);
	turtle e(5,6);
	turtle f(6,17);
	
	turtles.push_back(a);
	turtles.push_back(b);
	turtles.push_back(c);
	turtles.push_back(d);
	turtles.push_back(e);
	turtles.push_back(f);
	
	for (i = turtles.begin(); i != turtles.end(); ++i) i->Show();
	
	cout << "\n";
	
	sort(turtles.begin(), turtles.end(), compare_turtle_t); // What is wrong with this part?

	for (i = turtles.begin(); i != turtles.end(); ++i) i->Show();
	
}


The output is


1 10
2 13
3 8
4 24
5 6
6 17

Internal error: template function call __median failed algo.h(748)
*** Interpreter error recovered ***


I've tried to use this virtually word for word from the sort reference page example : http://www.cplusplus.com/reference/algorithm/sort/

and have tried to use the advice given on this other forum post: http://www.cplusplus.com/forum/beginner/4817/

Also, I should note it gives me the same error whether compare_turtle_t takes hit or hit&.

But I still can't figure out what I'm doing wrong. I feel like I've got to be pretty close but I'm not sure what's going on.
Last edited on
Try:
1
2
3
bool compare_turtle_t(const turtle& a, const turtle& b) {
	return (a.t < b.t);
}
Same error.
That's odd, it works fine for me. Can you post the whole error message?
That is the whole error message. Lol.

The compiler I'm using is ROOT - could that have something to do with it?
I've never used ROOT. Perhaps you could try:
 
	sort(turtles.begin(), turtles.end(), &compare_turtle_t); 

Otherwise I'm stumped.
That didn't work either. I changed it around a little bit and got a different error... took out the compare_turtle_t function and instead defined a < for turtles:

1
2
3
4
5
6
7
8
9
10
11
struct turtle {
	...
	bool operator<(turtle rhs) { return (t < rhs.t); }
	...
};

void test() {
	...
	sort(turtles.begin(), turtles.end());
	...
}


Now I'm getting

1 10
2 13
3 8
4 24
5 6
6 17

Error: Function __linear_insert(first,i,value_type(first)) is not defined in cur
rent scope  algo.h(814)
*** Interpreter error recovered ***


Does that help at all?
Last edited on
closed account (DSLq5Di1)
http://root.cern.ch/phpBB3/viewtopic.php?f=3&t=6336
http://root.cern.ch/phpBB3/viewtopic.php?f=3&t=12932

Seems to be an issue with the interpreter.
Topic archived. No new replies allowed.