473,549 Members | 2,723 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sort and get index?

In matlab, the sort function returns two things:

[a,b]=sort([5, 8, 7])

a = 5 7 8
b = 1 3 2

where a is the sorted result, and b is the corresponding index.
Is there C++ code available to achieve this?
Better compatible with STL vector.
Thanks
Jul 22 '05 #1
8 7581
"b83503104" <b8*******@yaho o.com> wrote...
In matlab, the sort function returns two things:

[a,b]=sort([5, 8, 7])

a = 5 7 8
b = 1 3 2

where a is the sorted result, and b is the corresponding index.
Is there C++ code available to achieve this?


Probably. You could simply sort pairs based on their 'first'
members, then get the 'second' members (which you should set
to ordinal numbers before sorting).

V
Jul 22 '05 #2
Me
template<class T> struct index_cmp {
index_cmp(const T arr) : arr(arr) {}
bool operator()(cons t size_t a, const size_t b) const
{ return arr[a] < arr[b]; }
const T arr;
};

vector<int> a;
a.push_back(5); a.push_back(8); a.push_back(7);

vector<size_t> b;
for (unsigned i = 0; i < a.size(); ++i)
b.push_back(i);
// b = [0, 1, 2]
sort(b.begin(), b.end(), index_cmp<vecto r<int>&>(a));
// b = [0, 2, 1]

then just offset into the a vector with the indices in b. I recomend
just sorting the indices this way and not touching the a vector.
Jul 22 '05 #3
b8*******@yahoo .com (b83503104) wrote in message
In matlab, the sort function returns two things:

[a,b]=sort([5, 8, 7])

a = 5 7 8
b = 1 3 2

where a is the sorted result, and b is the corresponding index.
Is there C++ code available to achieve this?
Better compatible with STL vector.
Thanks


There is no such way in C++. But you can build it yourself.

Here is one suggestion: make your original vector { 5, 8, 7 }, make a
vector of pointers { &orig[0], &orig[1], &orig[2] }, sort the vector
of pointers using std::sort of 3 arguments which should yield {
&orig[0], &orig[2], &orig[1] }.

A second suggestion is: make your original vector a vector of
pair<int, index> as { {5,0}, {8,1}, {7,2} }, sort the vector using
std::sort of 3 arguments which should yield { {5,0}, {7,2}, {8,1} }.

The first way would look something like this:

std::vector<int > orig;
orig.push_back( 5);
orig.push_back( 7);
orig.push_back( 8);
std::vector<con st int *> pointer;
pointer.reserve (orig.size());
const int *const start = &orig[0];
const int *const end = start + orig.size();
for (int * iter = start; iter != end; ++iter) pointer.push_ba ck(iter);
std::sort(point er.begin(), pointer.end(), LessDereference ());

where

struct LessDereference {
template <class T>
bool operator()(cons t T * lhs, const T * rhs) const {
return *lhs < *rhs;
}
};

To print the results, choose whatever option you want. There are many
ways, and here is one:

for (int i=0; i<pointer.size( ); i++) {
const int * p = pointer[i];
cout << "(" << *p << "," << p-start << " ";
}
Jul 22 '05 #4
b8*******@yahoo .com (b83503104) wrote in message
In matlab, the sort function returns two things:

[a,b]=sort([5, 8, 7])

a = 5 7 8
b = 1 3 2

where a is the sorted result, and b is the corresponding index.
Is there C++ code available to achieve this?
Better compatible with STL vector.
Thanks


There is no such way in C++. But you can build it yourself.

Here is one suggestion: make your original vector { 5, 8, 7 }, make a
vector of pointers { &orig[0], &orig[1], &orig[2] }, sort the vector
of pointers using std::sort of 3 arguments which should yield {
&orig[0], &orig[2], &orig[1] }.

A second suggestion is: make your original vector a vector of
pair<int, index> as { {5,0}, {8,1}, {7,2} }, sort the vector using
std::sort of 3 arguments which should yield { {5,0}, {7,2}, {8,1} }.

The first way would look something like this:

std::vector<int > orig;
orig.push_back( 5);
orig.push_back( 7);
orig.push_back( 8);
std::vector<con st int *> pointer;
pointer.reserve (orig.size());
const int *const start = &orig[0];
const int *const end = start + orig.size();
for (int * iter = start; iter != end; ++iter) pointer.push_ba ck(iter);
std::sort(point er.begin(), pointer.end(), LessDereference ());

where

struct LessDereference {
template <class T>
bool operator()(cons t T * lhs, const T * rhs) const {
return *lhs < *rhs;
}
};

To print the results, choose whatever option you want. There are many
ways, and here is one:

for (int i=0; i<pointer.size( ); i++) {
const int * p = pointer[i];
cout << "(" << *p << "," << p-start << " ";
}
Jul 22 '05 #5
an************* ****@yahoo.com (Me) wrote in message
template<class T> struct index_cmp {
index_cmp(const T arr) : arr(arr) {}
bool operator()(cons t size_t a, const size_t b) const
{ return arr[a] < arr[b]; }
const T arr;
};
Maybe class index_cmp could hold a const reference rather than an
object (ie. change const T arr to const T& arr). Saves unnecessary
copying.
sort(b.begin(), b.end(), index_cmp<vecto r<int>&>(a));


You can provide rename index_cmp to index_cmp_t and provide an inline
function

template <class Container>
inline
index_cmp_t<Con tainer>
index_cmp(const Container& c)
{
return index_cmp_t<Con tainer>(c);
}

This prevents the need to explicitly qualify template parameters in
the code.
Jul 22 '05 #6

"b83503104" <b8*******@yaho o.com> wrote in message
news:73******** *************** ***@posting.goo gle.com...
In matlab, the sort function returns two things:

[a,b]=sort([5, 8, 7])

a = 5 7 8
b = 1 3 2

where a is the sorted result, and b is the corresponding index.
Is there C++ code available to achieve this?
Better compatible with STL vector.
Thanks


Try the following untested code after installing boost from www.boost.org.

#include <map>
#include <boost/bind.hpp>
#include <boost/iterator/counting_iterat or.hpp>

typedef std::map<int,in t> tMap; // <data,index>

tMap Map;

int Data[] = { 5, 8, 7 };

std::transform( &data[0], &data[3]
, boost::counting _iterator<int>( 1)
, std::inserter<t Map>(Map)
, boost::bind( std::make_pair< int,int>, _1, _2 )
);

for( tMap::const_ite rator lItr = Map.begin() ; lItr != Map.end() ; ++lItr )
{
std::cout << "Data Value: " << lItr->first
<< " At Index: " << lItr->second;
}

Jeff F
Jul 22 '05 #7
Me
> Maybe class index_cmp could hold a const reference rather than an
object (ie. change const T arr to const T& arr). Saves unnecessary
copying.
sort(b.begin(), b.end(), index_cmp<vecto r<int>&>(a));


It does hold a const reference (notice the '&' at the call to sort). I
did it this way because doing it the way I would do in real life (add
a reference only if T isn't a pointer or a reference) requires a lot
more code or a dependency on boost's type_traits (which will hopefully
be added to the next standard).
Jul 22 '05 #8
an************* ****@yahoo.com (Me) wrote in message
Maybe class index_cmp could hold a const reference rather than an
object (ie. change const T arr to const T& arr). Saves unnecessary
copying.
sort(b.begin(), b.end(), index_cmp<vecto r<int>&>(a));


It does hold a const reference (notice the '&' at the call to sort). I
did it this way because doing it the way I would do in real life (add
a reference only if T isn't a pointer or a reference) requires a lot
more code or a dependency on boost's type_traits (which will hopefully
be added to the next standard).


Good point, sorry missed it.
Jul 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
4470
by: P Adhia | last post by:
Hello, If the explain shows that DB2 needs to sort the result of a cursor, does that always happen? i.e. if the resultset of the cursor is empty, does the sort have any overhead? It appears that, majority of the time is spent in allocation and deallocation of the temporary file to hold the data for the sort. Do these activities still take...
4
2797
by: PCHOME | last post by:
Hi! I have questions about qsort( ). Is anyone be willing to help? I use the following struct: struct Struct_A{ double value; ... } *AA, **pAA;
5
2829
by: Jan Smith | last post by:
I've searched the overloads for the Array.Sort method, and I haven't found a clear answer to my question. Maybe it's not in Array.Sort. Here's the question: I initialize an array X with the values 28 142 3 17 225. I can sort this array in ascending order and it will return 3 17 28 142 225. But I want a method that will return the...
1
3539
by: wapsiii | last post by:
is it possible to sort a dataview by a column index? Instead of this: dv.Sort = "Id"; I'd like to do this: dv.Sort = 0; // where 0 is column index /M
3
4489
by: gilly3 | last post by:
I have a column in a DataView that contains NaN. When I attempt to Sort on this column, I get: MESSAGE: Index was outside the bounds of the array. SOURCE: System.Data STACKTRACE: at System.Data.Index.Sort(Int32 left, Int32 right) at System.Data.Index.InitRecords() at System.Data.Index..ctor(DataTable table, Int32 indexDesc,...
48
4419
by: Alex Chudnovsky | last post by:
I have come across with what appears to be a significant performance bug in ..NET 2.0 ArrayList.Sort method when compared with Array.Sort on the same data. Same data on the same CPU gets sorted a lot faster with both methods using .NET 1.1, that's why I am pretty sure its a (rather serious) bug. Below you can find C# test case that should...
2
3965
by: gonzo | last post by:
So I have a project where I'm supposed to have a .txt input file of no more than ten first names, last names and birth years, and than in a menu I'm to give the user some options as to how the strings can be sorted. My problem is kind of hard to understand, so please bear with me. I've figured out how to sort the last names, first names and birth...
0
8511
Ganon11
by: Ganon11 | last post by:
Earlier, mmccarthy was kind enough to post a short article explaining the Bubble Sort. As she said, this is a relatively slow sorting algorithm. Here, I will attempt to present a slightly faster algorithm called Selection Sort. Imagine you have a list of numbers in random order. You want to sort these numbers in increasing order - that is,...
3
5164
by: aRTx | last post by:
I have try a couple of time but does not work for me My files everytime are sortet by NAME. I want to Sort my files by Date-desc. Can anyone help me to do it? The Script <? /* ORIGJINALI
0
7520
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7450
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7720
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7957
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7470
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5088
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3500
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3481
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.