• 0

[C++] Sorting two dimensional array


Question

I have two dimensional array which I would like to sort by the 2nd column.

Array consists of two columns - IDs and values.

It looks like this

1 21

2 6

3 54

4 65

5 11

... ...

and I would like to get an output like this:

4 65

3 54

1 21

5 11

2 6

I tried to follow cplusplus.com sort reference, but I can't rebuild it for my needs.

Link to comment
https://www.neowin.net/forum/topic/863170-c-sorting-two-dimensional-array/
Share on other sites

4 answers to this question

Recommended Posts

  • 0

You could simply use a sort routine for a 1-dimensional array, but repeat each sort movement in the second "column" too, so you're only sorting on the first dimension of the array, but the "rows" stay synchronised.

  • 0

If you don't feel like coding a sort routine, this can be done using temporary STL vectors:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int arr[5][2] = { { 1, 21 }, { 2, 6 }, { 3, 54 }, { 4, 65 }, { 5, 11 } };

bool mySortFunction(const vector<int>& inner1, const vector<int>& inner2) {
	return inner1[1] < inner2[1];
}

int main() {
	vector<vector<int> > vect;
	for (int i = 0; i < 5; ++i) {
		vector<int> inner(arr[i], arr[i] + 2);
		vect.push_back(inner);
	}

	sort(vect.begin(), vect.end(), mySortFunction);

	for (int i = 0; i < 5; ++i) {
		arr[i][0] = vect[i][0];
		arr[i][1] = vect[i][1];
	}
}

Keep in mind though that this implies a lot of unnecessary memory allocation and freeing, which can slow down the process tremendously. This isn't due to the STL being inefficient (it isn't), but creating a lot of vectors on the fly can't be very fast, unless you start writing your own memory allocators, but that's starting to look uglier than coding your own sort routine.

Edited by Dr_Asik
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Hello, The Nvidia Founders Edition 3080 video card is approximately six years old, correct? Have you looked into whether replacement fans are available for it? Perhaps replacing those will improve cooling, especially when combined with cleaning the card's heatsink and replacing the thermal interface materials. Regards, Aryeh Goretsky  
    • Hello, While ~104 GB of space may seem generous (at least compared to other e-readers which have 8-32GB), I feel at this price point the device should have a Micro SDXC card slot for expansion, particularly if it allows audio books to be installed and played. I hope to see more reviews of 6" phone-sized e-readers on Neowin in the future. It will be interesting to see how they compare. Regards, Aryeh Goretsky
    • Sandboxie Plus 1.17.8 / Classic 5.72.8 by Razvan Serea Run programs in a sandbox to prevent malware from making permanent changes to your PC. Sandboxie allows you to run your browser, or any other program, so that all changes that result from the usage are kept in a sandbox environment, which can then be deleted later. Sandboxie is a sandbox-based isolation software for 32- and 64-bit Windows NT-based operating systems. It is being developed by David Xanatos since it became open source, before that it was developed by Sophos (which acquired it from Invincea, which acquired it earlier from the original author Ronen Tzur). It creates a sandbox-like isolated operating environment in which applications can be run or installed without permanently modifying the local or mapped drive. An isolated virtual environment allows controlled testing of untrusted programs and web surfing. Sandboxie is available in two flavors Plus and Classic. Both have the same core components, this means they have the same level of security and compatibility. What's different is the user interface the Plus build has a modern Qt based UI which supports all new features that have been added since the project went open source. The Classic build has the old no longer developed MFC based UI, hence it lacks support for modern features, these features can however still be used when manually configured in the Sandboxie.ini. Sandboxie Plus 1.17.8 / Classic 5.72.8 release notes: Added added DisableCustomTitleOpt=[process,][y|n] to allow [#] sandboxie title markers on custom-titlebar windows (Delphi VCL, Qt, Electron) that were previously skipped to prevent DWM repaint CPU loops #5387 Changed updated bundled ImDisk driver to 3.0.2 #5419 Fixed fix Suppress logs for expected non-user SIDs #5422 SbieSvc.exe: SBIE2218/2219 error when run program as administrator #5417 fixed explorer.exe crashes in Application Compartment when Huorong Security is installed #5423 Download: Sandboxie Plus (64-bit) | 23.5 MB (Open Source) Download: Sandboxie Classic (64-bit) | 3.0 MB Links: Sandboxie Website | GitHub | ARM64 | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Hello, Christian Maas' XVI32 is a nice (and very small) hex editor. Speaking of hex editors, many years ago a colleague and I who both worked at Tribal Voice managed to edit a copy of the company's PowWow instant messaging client to make it behave better now that all of its lookup servers and other server-side tech was gone.  The program didn't support NAT (RFC-3022 was introduced in January 2001, the same time Tribal Voice was shuttered), but it still worked okay if you manually set up port-forwarding on your router.  The server at http://powwow.jazy.net/ hosts a copy (usual warnings about downloading and running untrusted code from random internet servers apply). I occasionally use some tools like Funduc Software's Search and Replace and Application Mover when I need to make mass-edits to text-based files or move programs with a hard-coded installation directories, respectively.  When I need to figure out the exact LCD panel inside of a laptop, EnTech Taiwan's Monitor Asset Manager is my go-to tool for that purpose. JD Design's website (now hosted on github.io) has a number of interesting freeware and shareware utilities.  I used to use their TouchPro utility to set the file timestamps on software I was mastering to match its version number (e.g., version 3.00 of a program had all of its files dates set to 3:00AM, and so forth). Karenware has a number of interesting freeware utilities, too. Regards, Aryeh Goretsky  
    • I still use HexChat! Not really as ancient as the 1994 AutoCAD above my post, but I have never found anything better to replace it. Yes we still operate an IRC server https://www.neowin.net/irc/ 😛 
  • Recent Achievements

    • Week One Done
      Jeroen Wilms earned a badge
      Week One Done
    • Week One Done
      rolfus earned a badge
      Week One Done
    • One Month Later
      Leroy Jethro Gibbs earned a badge
      One Month Later
    • Conversation Starter
      flexorcist earned a badge
      Conversation Starter
    • One Month Later
      AndreaB earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      509
    2. 2
      +Edouard
      198
    3. 3
      PsYcHoKiLLa
      138
    4. 4
      ATLien_0
      90
    5. 5
      Steven P.
      82
  • Tell a friend

    Love Neowin? Tell a friend!