set comparison method for class variable

J

jcteague

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
 
J

John Harrison

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
 
J

John Harrison

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; }
private:
set<int, Comp> selectedElements;
vector<int> x;
};

inline bool Comp::eek:perator()(int a, int b) const
{
return ptr->getX(a) < ptr->getX(b);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top