inline bool operator < declaration

Hi all, i am doing the following.

struct Adjacent
{
string name1;
int distance1,fare1;

};

inline bool operator<(const Adjacent &m, const Adjacent &n)
{
return (m.distance1 < n.distance1) && (m.fare1 < n.fare1);
}


I want to sort the two queue's one by fare and other by distance at same time or in same program. May be i need to return boolean operator( if i am right ) for each operation. I tried some combination but dint work any.
in the case above it displays the result according to fare sort.

Someone please help me for this ASAP.. Thanks alot.
You need to pass a sort predicate to each container, rather than using a global operator< for your type.
could you please give me an example how to use sort predicate for each container .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct FairLess
{
    bool operator()(const Adjacent &m, const Adjacent &n){
           return m.fare1 < n.fare1;
    }
};

struct DistanceLess
{
    bool operator()(const Adjacent &m, const Adjacent &n){
           return m.distance1 < n.distance1;
    }
};


queue<Adjacent> myQueue;
std::sort(myQueue.begin(),myQueue.end(),FairLess); //Sorted by fair 


Did not compile any of this code
Last edited on
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
44
45
46
47
48
49
50
51
52
#include <algorithm>
#include <vector>
#include <string>
#include <ostream>
#include <iostream>

struct Rec
{
	Rec(const std::string &name, int id) : name(name), id(id) {}

	std::string name;
	int id;
};

std::ostream& operator<<(std::ostream &os, const Rec &rec)
{
	os << rec.name << ' ' << rec.id;
	return os;
}

typedef std::vector<Rec> RecV;

bool SortByName(const Rec &a, const Rec &b)
{
	return a.name < b.name;
}

bool SortById(const Rec &a, const Rec &b)
{
	return a.id < b.id;
}

int main()
{
	RecV recs;
	recs.push_back(Rec("Nadine", 4));
	recs.push_back(Rec("Donnet", 2));
	recs.push_back(Rec("Ray", 3));
	recs.push_back(Rec("Dane", 7));

	std::sort(recs.begin(), recs.end(), SortByName);
	std::cout << "Sort by name" << std::endl;
	for (RecV::const_iterator p = recs.begin();  p != recs.end(); ++p)
		std::cout << *p << std::endl;

	std::sort(recs.begin(), recs.end(), SortById);
	std::cout << "Sort by id" << std::endl;
	for (RecV::const_iterator p = recs.begin();  p != recs.end(); ++p)
		std::cout << *p << std::endl;

	return 0;
}
Great HELP Folks !!!

I tried second approach it worked smoothly ... Thanks a ton .. I am done with the assignment :)


With the first one I was facing error..like Fairless not declared in this scope while passing in sort method.

....
Could any one please post some link where I can read about the functionality of the same . !

I just used it but not clear how it is working.
Topic archived. No new replies allowed.