473,378 Members | 1,384 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

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 7568
"b83503104" <b8*******@yahoo.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()(const 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<vector<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<const 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_back(iter);
std::sort(pointer.begin(), pointer.end(), LessDereference());

where

struct LessDereference {
template <class T>
bool operator()(const 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<const 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_back(iter);
std::sort(pointer.begin(), pointer.end(), LessDereference());

where

struct LessDereference {
template <class T>
bool operator()(const 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()(const 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<vector<int>&>(a));


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

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

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

"b83503104" <b8*******@yahoo.com> wrote in message
news:73**************************@posting.google.c om...
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_iterator.hpp>

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

tMap Map;

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

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

for( tMap::const_iterator 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<vector<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<vector<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
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...
4
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
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...
1
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
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...
48
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...
2
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...
0
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...
3
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
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.