472,958 Members | 2,662 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Multi-column sort (urgent help needed)

Hello All,

I am reading a CSV (comma seperated value) file into a 2D array. I want
to be able to sort multiple columns (ala Excel), so I know for starters,
I cant be using the array, I need something more sophistictated like a
vector of row objects.

The data is of this format (same number of columns for each row):

A, x, y, z, ...
A, b, c, f, ...
A, s, b, m, ...
C, p, s, w, ...
C, a, s, u, ....

etc ...

Esentially, what I want to do is :

1). Read the data into memory (no brainer - I can do that)
2). Sort the data by specified columns (say column 2, and 4)

I would be very grateful if any one could show me how to do this using a
simple code example, or point me to a URL for some examples, or better
still point me to a library that is capable of doing this.

Many thanks in advance for your help

Ann

Jul 22 '05 #1
5 8902
You could use a public domain database library like
http://www.sqlite.org. "SQLite is a small C library that implements a
self-contained, embeddable, zero-configuration SQL database engine."
Jul 22 '05 #2
Dr. Ann Huxtable wrote:
I am reading a CSV (comma seperated value) file into a 2D array. I want
to be able to sort multiple columns (ala Excel), so I know for starters,
I cant be using the array, I need something more sophistictated like a
vector of row objects.

The data is of this format (same number of columns for each row):

A, x, y, z, ...
A, b, c, f, ...
A, s, b, m, ...
C, p, s, w, ...
C, a, s, u, ....

etc ...

Esentially, what I want to do is :

1). Read the data into memory (no brainer - I can do that)
2). Sort the data by specified columns (say column 2, and 4)

I would be very grateful if any one could show me how to do this using a
simple code example, or point me to a URL for some examples, or better
still point me to a library that is capable of doing this.


Look up the std::sort algorithm in the C++ Standard Library.

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 22 '05 #3
In article <co**********@titan.btinternet.com>,
Dr. Ann Huxtable <an*********@research.de.edu> wrote:

I am reading a CSV (comma seperated value) file into a 2D array. I want
to be able to sort multiple columns (ala Excel), so I know for starters,
I cant be using the array, I need something more sophistictated like a
vector of row objects.
Yes, a vector of struct or class objects that represent rows, would be
more appropriate for this.
2). Sort the data by specified columns (say column 2, and 4)


You need to supply a custom comparison function to the standard sort()
function. Here's an example that I gave my students last year. Each
comparison function sorts by one field (column) only; to sort by more than
one field together, expand the comparison logic in the
function accordingly.

// profsort.cpp
//
// Demonstrates how to sort a vector of classes by supplying (a) a
// comparision function or (b) a comparison function object to the
// standard sort() function.
//----------------------------------------------------------------------

#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

//---------------------------------------------------------------------
// a simple class for storing data about professors

class Professor
{
public:
Professor (const string& initFN, const string& initLN,
const string& initOffice);
void Display() const;
friend int CompareByLastName (const Professor& lhs,
const Professor& rhs);
friend class CompareByOffice;
private:
string lastName, firstName, office;
};

// Constructor

Professor::Professor (const string& initFN, const string& initLN,
const string& initOffice)
: lastName(initLN), firstName(initFN), office(initOffice) {}

// A simple one-line display

void Professor::Display() const
{
cout << setw (15) << lastName
<< setw (10) << firstName
<< setw (20) << office
<< '\n';
}

// Comparison function for sorting by last name; it needs to
// be a friend function so it can access private data of the class

int CompareByLastName (const Professor& lhs, const Professor& rhs)
{
return (lhs.lastName < rhs.lastName);
}

// Here's another way to set up the comparison: a function object.
// This one compares by office location. This class needs to be
// a friend class of Professor so it can use private data.

class CompareByOffice
{
public:
int operator () (const Professor& lhs, const Professor& rhs)
{ return (lhs.office < rhs.office); };
};

//----------------------------------------------------------------------

void DisplayVector (const vector<Professor>& profs)
{
cout << '\n';
for (int k = 0; k < profs.size(); ++k)
{
profs[k].Display();
}
}

//----------------------------------------------------------------------
//----------------------------------------------------------------------

int main ()
{
ifstream profsfile ("profs.dat");
vector<Professor> profs;

// File format is one professor per line, with the fields separated
// by tabs

string firstName, lastName, office;
while (getline (profsfile, firstName, '\t')
&& getline (profsfile, lastName, '\t')
&& getline (profsfile, office, '\n'))
{
profs.push_back (Professor (firstName, lastName, office));
}
profsfile.close ();

cout << "\nBefore sorting:\n";
DisplayVector (profs);

// sort by last name, using an ordinary function for the comparison

sort (profs.begin(), profs.end(), CompareByLastName);

cout << "\nAfter sorting by last name:\n";
DisplayVector (profs);

// sort by office location, using a function object for the comparison

sort (profs.begin(), profs.end(), CompareByOffice());

cout << "\nAfter sorting by office:\n";
DisplayVector (profs);

cout << '\n';

return 0;
}

--
Jon Bell <jt*******@presby.edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
Jul 22 '05 #4
"Jon Bell" <jt*******@presby.edu> wrote in message
news:co**********@jtbell.presby.edu...
You need to supply a custom comparison function to the standard sort()
function. Here's an example that I gave my students last year. Each
comparison function sorts by one field (column) only; to sort by more than
one field together, expand the comparison logic in the
function accordingly.
I would like to make a single comment/addition to your (excellent) example.
int CompareByLastName (const Professor& lhs, const Professor& rhs)
{
return (lhs.lastName < rhs.lastName);
} .... class CompareByOffice
{
public:
int operator () (const Professor& lhs, const Professor& rhs)
{ return (lhs.office < rhs.office); };
};
If one would like to simultaneously sort by two columns (e.g. sort by office
first, but then by name within the same office), one will want to replace
the second call to sort below with std::stable_sort.
sort (profs.begin(), profs.end(), CompareByLastName);

cout << "\nAfter sorting by last name:\n";
DisplayVector (profs);

// sort by office location, using a function object for the comparison

sort (profs.begin(), profs.end(), CompareByOffice());

stable_sort( ...same params... ); // will keep names ordered within
office

Alternatively, a comparison object doing both ordering operations at once
can
be provided to a single sort() call:

int CompareByOfficeAndLastName (const Professor& lhs, const Professor& rhs)
{
return (lhs.office < rhs.office)
|| ( !(rhs.office < lhs.office) && (lhs.lastName <
rhs.lastName) );
// return result of name compare if office compare does not provide an
order
}

hth -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Jul 22 '05 #5


Jon Bell wrote:
In article <co**********@titan.btinternet.com>,
Dr. Ann Huxtable <an*********@research.de.edu> wrote:
I am reading a CSV (comma seperated value) file into a 2D array. I want
to be able to sort multiple columns (ala Excel), so I know for starters,
I cant be using the array, I need something more sophistictated like a
vector of row objects.

Yes, a vector of struct or class objects that represent rows, would be
more appropriate for this.

2). Sort the data by specified columns (say column 2, and 4)

You need to supply a custom comparison function to the standard sort()
function. Here's an example that I gave my students last year. Each
comparison function sorts by one field (column) only; to sort by more than
one field together, expand the comparison logic in the
function accordingly.

// profsort.cpp
//
// Demonstrates how to sort a vector of classes by supplying (a) a
// comparision function or (b) a comparison function object to the
// standard sort() function.
//----------------------------------------------------------------------

#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

//---------------------------------------------------------------------
// a simple class for storing data about professors

class Professor
{
public:
Professor (const string& initFN, const string& initLN,
const string& initOffice);
void Display() const;
friend int CompareByLastName (const Professor& lhs,
const Professor& rhs);
friend class CompareByOffice;
private:
string lastName, firstName, office;
};

// Constructor

Professor::Professor (const string& initFN, const string& initLN,
const string& initOffice)
: lastName(initLN), firstName(initFN), office(initOffice) {}

// A simple one-line display

void Professor::Display() const
{
cout << setw (15) << lastName
<< setw (10) << firstName
<< setw (20) << office
<< '\n';
}

// Comparison function for sorting by last name; it needs to
// be a friend function so it can access private data of the class

int CompareByLastName (const Professor& lhs, const Professor& rhs)
{
return (lhs.lastName < rhs.lastName);
}

// Here's another way to set up the comparison: a function object.
// This one compares by office location. This class needs to be
// a friend class of Professor so it can use private data.

class CompareByOffice
{
public:
int operator () (const Professor& lhs, const Professor& rhs)
{ return (lhs.office < rhs.office); };
};

//----------------------------------------------------------------------

void DisplayVector (const vector<Professor>& profs)
{
cout << '\n';
for (int k = 0; k < profs.size(); ++k)
{
profs[k].Display();
}
}

//----------------------------------------------------------------------
//----------------------------------------------------------------------

int main ()
{
ifstream profsfile ("profs.dat");
vector<Professor> profs;

// File format is one professor per line, with the fields separated
// by tabs

string firstName, lastName, office;
while (getline (profsfile, firstName, '\t')
&& getline (profsfile, lastName, '\t')
&& getline (profsfile, office, '\n'))
{
profs.push_back (Professor (firstName, lastName, office));
}
profsfile.close ();

cout << "\nBefore sorting:\n";
DisplayVector (profs);

// sort by last name, using an ordinary function for the comparison

sort (profs.begin(), profs.end(), CompareByLastName);

cout << "\nAfter sorting by last name:\n";
DisplayVector (profs);

// sort by office location, using a function object for the comparison

sort (profs.begin(), profs.end(), CompareByOffice());

cout << "\nAfter sorting by office:\n";
DisplayVector (profs);

cout << '\n';

return 0;
}

Thanks very much Jon, this is just what I needed !

Jul 22 '05 #6

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

Similar topics

4
by: OutsiderJustice | last post by:
Hi All, I can not find any information if PHP support multi-thread (Posix thread) or not at all, can someone give out some information? Is it supported? If yes, where's the info? If no, is it...
37
by: ajikoe | last post by:
Hello, Is anyone has experiance in running python code to run multi thread parallel in multi processor. Is it possible ? Can python manage which cpu shoud do every thread? Sincerely Yours,...
12
by: * ProteanThread * | last post by:
but depends upon the clique: ...
0
by: frankenberry | last post by:
I have multi-page tiff files. I need to extract individual frames from the multi-page tiffs and save them as single-page tiffs. 95% of the time I receive multi-page tiffs containing 1 or more black...
6
by: cody | last post by:
What are multi file assemblies good for? What are the advantages of using multiple assemblies (A.DLL+B.DLL) vs. a single multi file assembly (A.DLL+A.NETMODULE)?
2
by: ip4ram | last post by:
I used to work with C and have a set of libraries which allocate multi-dimensional arrays(2 and 3) with single malloc call. data_type **myarray =...
6
by: Joe | last post by:
I have 2 multi-list boxes, 1 displays course categories based on a table called CATEGORIES. This table has 2 fields CATEGORY_ID, CATEGORY_NAME The other multi-list box displays courses based on...
4
by: mimmo | last post by:
Hi! I should convert the accented letters of a string in the correspondent letters not accented. But when I compile with -Wall it give me: warning: multi-character character constant Do the...
5
by: bobwansink | last post by:
Hi, I'm relatively new to programming and I would like to create a C++ multi user program. It's for a project for school. This means I will have to write a paper about the theory too. Does anyone...
0
by: Sabri.Pllana | last post by:
We apologize if you receive multiple copies of this call for papers. *********************************************************************** 2008 International Workshop on Multi-Core Computing...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...
2
by: GKJR | last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...

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.