problem related to the sort function provided by STL

R

Rachel Forder

Hi All,

I have a problem related to the sort function provided by STL.

class A{
A(string, string, int);
string itemA;
string itemB;
int itemC;
};

class B{
vector<A*> vecData;
vector<int> itemASorted;//keeps vecData indexes into sorted form
for itemA
vector<int> itemBSorted;//keeps vecData indexes into sorted form
for temA
vector<int> itemCSorted;//keeps vecData indexes into sorted form
for itemA
};

In my program, i fill my vecData with all the data avalible.
then i need to create the 3 sorted vectors where the indexes into
vecData is kept in sorted form according to the item.

i am having problem in defining compare function for the 3rd argument
of STL sort function

sort(itemASorted.begin(), itemASorted.end(), cmpFunc);

approach 1:
make cmpFunc as static member of class B,
but then it won't be able to access vecData variable which is
not static.
approach 2:
overload operator(),
but it can be done only for one item...whereas i need a vector
sorted for all the 3 items

any guesses how can i perform sorting of my items?

thanks for any help!!
 
I

Ivan Vecerina

....
class A{
A(string, string, int);
string itemA;
string itemB;
int itemC;
};

class B{
vector<A*> vecData;
vector<int> itemASorted;//keeps vecData indexes into sorted form
for itemA
vector<int> itemBSorted;//keeps vecData indexes into sorted form
for temA
vector<int> itemCSorted;//keeps vecData indexes into sorted form
for itemA
};

In my program, i fill my vecData with all the data avalible.
then i need to create the 3 sorted vectors where the indexes into
vecData is kept in sorted form according to the item.

i am having problem in defining compare function for the 3rd argument
of STL sort function

sort(itemASorted.begin(), itemASorted.end(), cmpFunc); ....
any guesses how can i perform sorting of my items?

You can use an auxillary class, one for each ordering criterion:

// class for sorting by itemA member of class A
class OrderClassAItemA
{
vector<A*>* data_;
public:
OrderClassAItemA(vector<A*>& data) : data_(&data) {}
void operator()(int a, int b)
{
return data_->at(a)->itemA < data_->at(b)->itemA;
}
};

Which is then used as follows from a method of class B:
sort( itemASorted.begin(), itemASorted.end()
, OrderClassAItemA(vecData) );

One such class can be written for each sort order...


I hope this helps,
Ivan
 

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

Forum statistics

Threads
473,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top