By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,508 Members | 1,685 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,508 IT Pros & Developers. It's quick & easy.

set comparison method for class variable

P: n/a
I have a class that has a set<int> member variable. the items in the
set are selected indices of a vector. I would like to sort the set on
the values in the vector they point too. Here is a part of the header
file:

Class A{
public:
int getX(int i) //basic getter. gets value from vector

private
set<int> selectedElements;
vector<int> x
};

I have tried several variations with a set comparison function with no
luck. Any help would be greatly appreciated.

thanks,
John

Oct 30 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
jc******@gmail.com wrote:
I have a class that has a set<int> member variable. the items in the
set are selected indices of a vector. I would like to sort the set on
the values in the vector they point too. Here is a part of the header
file:

Class A{
public:
int getX(int i) //basic getter. gets value from vector

private
set<int> selectedElements;
vector<int> x
};

I have tried several variations with a set comparison function with no
luck. Any help would be greatly appreciated.

thanks,
John


It sounds a bit risky, what if the vector changes, then your set would
be out of order with undefined effects.

But in any case, you can't use a function for this purpose, you need a
functor, something like this should do

class Comp
{
public:
Comp(A* p) : ptr(p) {}
bool operator()(int a, int b) const
{
return p->getX(a) < p->getX(b);
}
private:
A* ptr;
};

class A
{
public:
A() : selectedElements(Comp(this)) {}
private:
set<int, Comp> selectedElements;
vector<int> x;
};

Untested code.

john
Oct 30 '05 #2

P: n/a
Here's a cleaned up version of the above code

class A;

class Comp
{
public:
Comp(A* p) : ptr(p) {}
bool operator()(int a, int b) const;
private:
A* ptr;
};

class A
{
public:
A() : selectedElements(Comp(this)) {}
int getX(int i) { return x[i]; }
private:
set<int, Comp> selectedElements;
vector<int> x;
};

inline bool Comp::operator()(int a, int b) const
{
return ptr->getX(a) < ptr->getX(b);
}
Oct 30 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.