 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
jcteague@gmail.com Guest
|
Posted: Sun Oct 30, 2005 9:12 pm Post subject: set comparison method for class variable |
|
|
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
|
|
| Back to top |
|
 |
John Harrison Guest
|
Posted: Sun Oct 30, 2005 11:00 pm Post subject: Re: set comparison method for class variable |
|
|
[email]jcteague (AT) gmail (DOT) com[/email] wrote:
| Quote: | 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
|
|
| Back to top |
|
 |
John Harrison Guest
|
Posted: Sun Oct 30, 2005 11:14 pm Post subject: Re: set comparison method for class variable |
|
|
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);
}
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|