473,782 Members | 2,479 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting two arrays with one call to sort()?


I have two separate arrays A and B. The comparison function only
depends on elements in A (keys are in A),
but the swap() function needs to swap not only A[i],A[j], but also
B[i],B[j] ; whenever it swaps A[i],A[j].
Can this be done using internal sort() of C++? If not, what is the
easiest way to accomplish this. Speed is
of paramount importance...co pying/merging the arrays is out of
question...

Thanks a lot for your help.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Sep 22 '07 #1
10 6190
"John" <we**********@y ahoo.comwrote in message
news:11******** **************@ g4g2000hsf.goog legroups.com...
>
I have two separate arrays A and B. The comparison function only
depends on elements in A (keys are in A),
but the swap() function needs to swap not only A[i],A[j], but also
B[i],B[j] ; whenever it swaps A[i],A[j].
Can this be done using internal sort() of C++? If not, what is the
easiest way to accomplish this. Speed is
of paramount importance...co pying/merging the arrays is out of
question...
Why isn't it a map? std::map<A, B>
Wouldn't that solve all your problems?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Sep 22 '07 #2
John wrote:
I have two separate arrays A and B. The comparison function only
depends on elements in A (keys are in A),
but the swap() function needs to swap not only A[i],A[j], but also
B[i],B[j] ; whenever it swaps A[i],A[j].
Can this be done using internal sort() of C++?
I should hope so, since the main point of the STL is to decouple algorithms
from data structures. Something like this ought to work:

struct double_iterator {

T* const a; U* const b; size_t i;

struct ref {
T& p; U& q;
ref(T& p, U& q) : p(p), q(q) {}
};

ref operator*() { return ref(a[i], b[i]); }

// ...

};

inline void operator=(ref x, ref y) { x.p = y.p; x.q = y.q; }
inline bool operator<(ref x, ref y) { return x.p < y.p; }

// ...

std::sort(doubl e_iterator(A,B, 0), double_iterator (A,B,size));

I think this will be as efficient as a hand-coded sort if you have a decent
compiler.

-- Ben

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Sep 22 '07 #3

on Sat Sep 22 2007, John <weekender_ny-AT-yahoo.comwrote:
I have two separate arrays A and B. The comparison function only
depends on elements in A (keys are in A),
but the swap() function needs to swap not only A[i],A[j], but also
B[i],B[j] ; whenever it swaps A[i],A[j].
Can this be done using internal sort() of C++? If not, what is the
easiest way to accomplish this. Speed is
of paramount importance...co pying/merging the arrays is out of
question...
You might be able to use boost::zip_iter ator for this
(http://boost.org/libs/iterator/doc/zip_iterator.html)

Depending on details of your STL implementation, you may run into
trouble because zip_iterator's reference type is a proxy, and the
current C++ standard does not require proxy references to work.
However, several STL implementations *do* work with proxy references
(and the next standard does require them to work). The likelihood is
that if the code compiles, it will also give correct results -- but
you should verify that by testing.

HTH,

--
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com

The Astoria Seminar ==http://www.astoriaseminar.com

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Sep 23 '07 #4
On Sep 22, 3:12 pm, Ben Rudiak-Gould <br276delet...@ cam.ac.ukwrote:
John wrote:
I havetwoseparate arraysA and B. The comparison function only
depends on elements in A (keys are in A),
but the swap() function needs to swap not only A[i],A[j], but also
B[i],B[j] ; whenever it swaps A[i],A[j].
Can this be doneusingintern alsort() of C++?

I should hope so, since the main point of the STL is to decouple algorithms
from data structures. Something like this ought to work:

struct double_iterator {

T* const a; U* const b; size_t i;

struct ref {
T& p; U& q;
ref(T& p, U& q) : p(p), q(q) {}
};

ref operator*() { return ref(a[i], b[i]); }

// ...

};

inline void operator=(ref x, ref y) { x.p = y.p; x.q = y.q; }
inline bool operator<(ref x, ref y) { return x.p < y.p; }

// ...

std::sort(doubl e_iterator(A,B, 0), double_iterator (A,B,size));

I think this will be as efficient as a hand-codedsortif you have a decent
compiler.
{ signature and clc++m banner removed - please remove them yourself. -mod }

Here is as far as I got, it still doesnt work :(

#include <iostream>

using namespace std;
const int N = 10;

template < typename tA, typename tB >
struct double_iterator {
tA* a;
tB* b;
size_t i;

struct ref {
tA& p; tB& q;
ref(tA& p, tB& q) : p(p), q(q) {};
void operator=(ref y){
p= y.p; q = y.q;
};
void operator<(ref y){
return p < y.p;
};
};

ref operator*(){ return ref(a[i],b[i]); }
double_iterator (tA* _a, tB* _b, size_t _i){
a = _a;
b = _b;
i = _i;
};
};
int main(void){
int A[N];
float B[N];

for (int i = 0; i < N; ++i){
A[i] = rand(); B[i] = A[i] % 10;
cout << "\t" << A[i] << "\t" << B[i] << endl;
}

std::sort(doubl e_iterator<int, float>(A,B,0),
double_iterator <int,float>(A,B ,N));

for (int i = 0; i < N; ++i){
cout << "\t" << A[i] << "\t" << B[i] << endl;
}

return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Sep 23 '07 #5
In article <11************ **********@g4g2 000hsf.googlegr oups.com>, John
<we**********@y ahoo.comwrote:
I have two separate arrays A and B. The comparison function only
depends on elements in A (keys are in A),
but the swap() function needs to swap not only A[i],A[j], but also
B[i],B[j] ; whenever it swaps A[i],A[j].
Can this be done using internal sort() of C++? If not, what is the
easiest way to accomplish this. Speed is
of paramount importance...co pying/merging the arrays is out of
question...

Thanks a lot for your help.
using boost::zip_iter ator looks like a solution that
allows the sort to work with const additional ram and
data is sorted. It requires a simple compare functor
since boost::tuple will compare the B entry if the A entries are equal.

see
http://boost.org/libs/iterator/doc/zip_iterator.html

typedef typename boost::tuple<A: :iterator,B::it eratoriter_tupl e;
// will use zip_iterator<it er_tuplevia make_zip_iterat or.

/*
sort || random access sequences A,B based on keyed on A only
should be fairly self explained:)
*/
struct compare_A_only
{
typedef typename boost::tuple<A: :value_type,B:: value_typearg;
bool operator (const arg &x,const arg &y) const
{
return boost::get<0>(x ) < boost::get<0>(y );
}
};
// ...
std::sort
(
boost::make_zip _iterator(iter_ tuple(a.begin() ,b.begin()),
boost::make_zip _iterator(iter_ tuple(a.end(),b .end()),
compare_A_only( )
};

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Sep 23 '07 #6

John <we**********@y ahoo.comwrote in message...

Please format (indent) your code. [ if you are using tabs, change them to
spaces for posting.]

Remove the extra semicolons, except where required.

You did not say what your problem is/was, or show the compiler errors (first
three).

FAQ http://www.parashift.com/c++-faq-lite
[ see section 5 ]

Thanks.
--
Bob R
POVrookie
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]

Sep 23 '07 #7
xz
On Sep 22, 12:42 pm, Erik Wikström <Erik-wikst...@telia. comwrote:
On 2007-09-22 16:52, xz wrote:

but by
using a vector you gain more functionality and have less limitations.
Is that always better? Even in the case you don't need those
functionality at all.
I thought, in the programming world, it's better for an object not to
have the function if it does not need the function.
>
--
Erik Wikström

Sep 24 '07 #8
xz
On Sep 22, 12:42 pm, Erik Wikström <Erik-wikst...@telia. comwrote:
On 2007-09-22 16:52, xz wrote:

but by
using a vector you gain more functionality and have less limitations.
Is that always better? Even in the case you don't need those
functionality at all.
I thought, in the programming world, it's better for an object not to
have the function if it does not need the function.
>
--
Erik Wikström

Sep 24 '07 #9
On 2007-09-24 20:30, xz wrote:
On Sep 22, 12:42 pm, Erik Wikström <Erik-wikst...@telia. comwrote:
>On 2007-09-22 16:52, xz wrote:

but by
using a vector you gain more functionality and have less limitations.

Is that always better? Even in the case you don't need those
functionality at all.
I thought, in the programming world, it's better for an object not to
have the function if it does not need the function.
If you would limit all objects to just provide the functionality you
require right now you would be in a lot of trouble, since most things
can do more than what you need. Also, by limiting the objects you make
it harder to extend the program in the future. One of the greatest
problems with arrays is that they have a fixes size, so if you find that
you need to have more elements in the array later on you will need to go
through all the code that uses the array and make sure that it works
with the new size, with a vector you do not usually have this problem.

But to answer you question, no it is not always better to use a vector
than an array. However those cases where it is not are pretty rare and
those who run into them usually recognise them when they seem them. To
date I have personally never been in such a situation, mostly because I
do not write programs where they arise.

--
Erik Wikström
Sep 24 '07 #10

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

Similar topics

3
1854
by: Terry Richards | last post by:
this is prolly too simple but i got a brain block i have two arrays, one is days and the other is timeofday,<each letter represents a time on the hour> how do is sort by days and put each day's list in order of time? so that i get a list in order of days and each day is in order of time...i can put in order by day or time but they always end up with whatever is the other order wrong. if ( isset($_GET) && $_GET=='call_days' ) {
7
3266
by: Federico G. Babelis | last post by:
Hi All: I have this line of code, but the syntax check in VB.NET 2003 and also in VB.NET 2005 Beta 2 shows as unknown: Dim local4 As Byte Fixed(local4 = AddressOf dest(offset)) CType(local4, Short) = CType(src, Short)
22
4171
by: mike | last post by:
If I had a date in the format "01-Jan-05" it does not sort properly with my sort routine: function compareDate(a,b) { var date_a = new Date(a); var date_b = new Date(b); if (date_a < date_b) { return -1; } else
7
3050
by: Karin Jensen | last post by:
Hi I am running a PHP program that connects to an Access 2000 database via ODBC: $results = odbc_exec($connection_id, $sql_select); Is it possible to sort the contents of $results? I wish to use a regex-based sort order that you can't do in Access 2000* SQL with "ORDER BY".
10
455
by: Roy Gourgi | last post by:
Hi, How would I sort an array? TIA Roy
7
1729
by: Noah Roberts | last post by:
I know there must be a way to do this using stl functions and not reinventing the sort loops and such but I need to sort several arrays side by side using one as the "key". Interested in ideas here... Two directions I can think of would be to create some sort of iterator or to create an object to wrap the value and index of the key array and then place these in a vector and sort it. Creating an iterator seems like maybe too complex but...
11
2019
by: Trent | last post by:
Running this I see that on first run, both bubble and selection sort have 9 sort counts while insertion sort has ZERO. With a sorted list, should this be ZERO for all? Also bsort and Ssort have the same exact sorting counts also..shouldn't they differ somewhat? Source and data file below. Thanks
4
1712
by: Trent | last post by:
Still have problems with this thing. Seems my results are not matching the "correct" example given. The three sets of numbers below the last 3 columns is suppose to be the number of comparisons made by eahc sorting function. I have having trouble getting the number of comparisons to match. One comment was that "the counts are in the wrongs place," but I have moved them all over the function and still they do not match.
3
7347
KevinADC
by: KevinADC | last post by:
If you are entirely unfamiliar with using Perl to sort data, read the "Sorting Data with Perl - Part One and Two" articles before reading this article. Beginning Perl coders may find this article uses unfamiliar terms and syntax. Intermediate and advanced Perl coders should find this article useful. The object of the article is to inform the reader, it is not about how to code Perl or how to write good Perl code, but to teach the Schwartzian...
5
3186
by: lemlimlee | last post by:
hello, this is the task i need to do: For this task, you are to develop a Java program that allows a user to search or sort an array of numbers using an algorithm that the user chooses. The search algorithms that can be used are Linear Search and Binary Search. The sorting algorithms are bubble, selection and Insertion sort. First, the user is asked whether he/she wants to perform a search option, a sort operation, or exit the program. If...
0
10146
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9942
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8967
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6733
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4043
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2874
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.