C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

how to return index of sorted vector

 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++)
View previous topic :: View next topic  
Author Message
Guest






PostPosted: Thu Dec 14, 2006 10:11 am    Post subject: how to return index of sorted vector Reply with quote



Hi, I am wondering if there is a simple and quick way to return the
indices of sorted vector.
for example, I have a vector<int> x containing {5, 2, 3, 0, 2}.
I can use

sort(x.begin(), x.end(), less<int>());

to sort the vector x. Then the sorted x becomes {0, 2, 2, 3, 5}. But
how can I obtain the indices of sorted x, which is {3, 1, 4, 2, 0}.

I know that I can insert each element of x paired with the index into a
multimap and read out the reordered indices. But that is not what I am
looking for since I do not want to spend memory to keep another copy of
my vector x in multimap.

Surapong L.
Back to top
Guest






PostPosted: Thu Dec 14, 2006 10:11 am    Post subject: Re: how to return index of sorted vector Reply with quote



boheman (AT) gmail (DOT) com wrote:
Quote:
Hi, I am wondering if there is a simple and quick way to return the
indices of sorted vector.
for example, I have a vector<int> x containing {5, 2, 3, 0, 2}.
....
to sort the vector x. Then the sorted x becomes {0, 2, 2, 3, 5}. But
how can I obtain the indices of sorted x, which is {3, 1, 4, 2, 0}.

Create a vector i = {0,1,2,3,4,5} of sort indexes (std::generate should
com in handy). Use the three argument sort, where the third argument
references your vector x, to compare the elements of i based not on
their own values but on the values they index in x:

class lt {
vector<int> &_x;
public:
lt( vector<int> & x ) : _x(x) {}
bool comp( int j, int k ) const { return _x[j] < _x[k]; }
};
....
sort( i.begin(), i.end(), lt(x) );

Incidentally, APL has a "grade" primitive which does exactly this.
Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ language (comp.lang.c++) All times are GMT
Page 1 of 1

 
Jump to:  
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


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.