 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Guest
|
Posted: Thu Dec 14, 2006 10:11 am Post subject: how to return index of sorted vector |
|
|
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
|
Posted: Thu Dec 14, 2006 10:11 am Post subject: Re: how to return index of sorted vector |
|
|
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 |
|
 |
|
|
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
|
|