473,385 Members | 1,492 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,385 software developers and data experts.

vector and sort problem

Hi,

Why does my vector not sort. What I understand is you have to overload
the < operator, but that does not work.

see code below

Thanks

Johan

class Demo
{
public :
Demo(string filename) : filename(filename)
{
}

bool operator<(const Demo& d)
{
return filename < d.filename;
}

string getFilename()
{
return filename;
}

private :
string filename;
};

int main(int argc, char** argv[])
{
vector<Demo*> v;

v.push_back(new Demo("z"));
v.push_back(new Demo("c"));
v.push_back(new Demo("a"));
v.push_back(new Demo("v"));
v.push_back(new Demo("t"));
v.push_back(new Demo("g"));

sort(v.begin(), v.end());
typedef vector<Demo*>::const_iterator iter;
for(iter i = v.begin(); i != v.end(); i++)
{
cout << (*i)->getFilename() << endl;
}

return 0;
}

output

z
c
a
v
g
t

Johan
Jul 23 '05 #1
4 1881
Johan wrote:
Hi,

Why does my vector not sort. What I understand is you have to overload
the < operator, but that does not work.
Overloading < is one way to do it.

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

using std::string;
using std::cout;
using std::endl;
using std::sort;
using std::vector;
class Demo
{
public :
Demo(string filename) : filename(filename)
{
}

bool operator<(const Demo& d)
bool operator<(const Demo& d) const
{
return filename < d.filename;
}

string getFilename()
string getFilename() const
{
return filename;
}

private :
string filename;
};

int main(int argc, char** argv[])
{
vector<Demo*> v;
Your element type is not Demo, but pointer to Demo. So the vector will be
sorted by pointer values.
v.push_back(new Demo("z"));
v.push_back(new Demo("c"));
v.push_back(new Demo("a"));
v.push_back(new Demo("v"));
v.push_back(new Demo("t"));
v.push_back(new Demo("g"));

sort(v.begin(), v.end());
If you want to store pointers, you have to provide as a third parameter to
sort a comparison function/functor, since you cannot overload operator< for
pointers. Add before main:

struct cmp
{
bool operator()(const Demo* lhs, const Demo* rhs) const
{
return *lhs < *rhs;
}
};

And then replace your sort with:

sort(v.begin(), v.end(), cmp());

typedef vector<Demo*>::const_iterator iter;
for(iter i = v.begin(); i != v.end(); i++)
{
cout << (*i)->getFilename() << endl;
}

return 0;
}


You don't delete the elements. In this case, it won't make much of a
difference, but it's good to get used to cleaning up after yourself.

Jul 23 '05 #2
"Johan" <jo***********@ns.nl> wrote in message
news:cd**************************@posting.google.c om...
Why does my vector not sort. What I understand is you have to overload
the < operator, but that does not work.

As a complement to Rolf's accurate comment, I would just
like to point out that using a vector of values (instead
of pointers) might be a better solution:

int main(int argc, char** argv[])
{
vector<Demo> v;

v.push_back(Demo("z"));
v.push_back(Demo("c"));
v.push_back(Demo("a"));
v.push_back(Demo("v"));
v.push_back(Demo("t"));
v.push_back(Demo("g"));

sort(v.begin(), v.end());
typedef vector<Demo>::const_iterator iter;
for(iter i = v.begin(); i != v.end(); i++)
{
cout << i->getFilename() << endl;
}
return 0;
}

Fewer memory allocations, and no memory leaks.
Cheers,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Jul 23 '05 #3
Johan wrote:
Hi,

Why does my vector not sort. What I understand is you have to overload the < operator, but that does not work.
It works just fine -- but you've defined your collection in a way that
prevents it from ever being used.

[ ... ]
bool operator<(const Demo& d)
{
return filename < d.filename;
}
This is fine -- it compares one Demo to another just like it should.
string getFilename()
{
return filename;
}
It's only minimally related to the problem at hand, but this is not
nearly so fine -- it exposes the class' internals to the outside world.

[ ... ]
vector<Demo*> v;
Here's your real problem: up above, you've defined how to compare one
Demo to another, but here you're not storing Demo's -- you're storing
pointers to Demo's instead.

There are two ways to deal with this. If it's really crucial that you
store pointers (e.g. you really have a polymorphic hierarchy with Demo
as the base class) then you need to define a function/functor to do the
comparison:

bool cmp(Demo const &a, Demo const &b) {
return a.getFileName() < b.GetFileName();
}

and then when you sort the vector, tell sort to use that to do the
comparisons:

std::sort(v.begin(), v.end(), cmp);

It's usually better, however, to simply store objects instead of
pointers, which will allow your operator< to do the job:

vector<Demo> v;

std::sort(v.begin(), v.end());

As it stands right now, std::sort is comparing the _pointers_ rather
than the Demo's themselves -- in practical terms, this means it's
sorting them into the order in which they're stored in memory, though
from a technical viewpoint, it's simply undefined behavior.
sort(v.begin(), v.end());
typedef vector<Demo*>::const_iterator iter;
for(iter i = v.begin(); i != v.end(); i++)
{
cout << (*i)->getFilename() << endl;
}


Here's why having a (public) getFilename is really a bad idea: now the
rest of your code knows about, and makes use of the internals of a Demo
instead of treating it as an object in its own right. I'd prefer to do
something like:

class Demo {
// your "stuff" but with getFilename private or removed.
public:
friend ostream &operator<<(ostream &os, Demo const &d);
};

ostream &operator<<(ostream &os, Demo const &d) {
return os << d.getFilename();
}

and then when you want to print out your sorted vector of demos, you
can write code that actually writes out the Demos:

for(iter i = v.begin(); i != v.end(); i++)
{
cout << *i << endl;
}

or better yet, use an algorithm and write even less yourself:

std::copy(v.begin(), v.end(), ostream_iterator<Demo>(cout, "\n"));

--
Later,
Jerry.

The universe is a figment of its own imagination.

Jul 23 '05 #4

[snip]
string getFilename()
{
return filename;
}
It's only minimally related to the problem at hand, but this is not
nearly so fine -- it exposes the class' internals to the outside world.


Hmm .. I am not sure I agree. All the getFilename function does is
provide a way to obtain a string (by value), from the object. This does not
say anything about the internals of the Demo class, and it seems quite
reasonable, given that filenames are commonly represented as strings. For
all we know, the string returned by getFilename could be generated at random
(although that would not be very useful).
If you are actually talking about the "in place" definition of the
function, then ok, point taken. But the OP may well have presented it that
way for the sake of simplicity. Certainly if the class is handled in the
canonical way (declarations in .hpp, definitions in .cpp), then there is no
reason that the internal representation of the class can't be changed, given
the definition of getFilename above. As long as getFilename returns a
string, nothing will need to be changed in applications using Demo objects.

[snip]
Here's why having a (public) getFilename is really a bad idea: now the
rest of your code knows about, and makes use of the internals of a Demo
instead of treating it as an object in its own right. I'd prefer to do
something like:
Again, I don't agree that getFilename exposes the representation of the
class(see above). However, I *do* agree that your suggested method below
for handling this particular example is generally a better approach.

class Demo {
// your "stuff" but with getFilename private or removed.
public:
friend ostream &operator<<(ostream &os, Demo const &d);
};

ostream &operator<<(ostream &os, Demo const &d) {
return os << d.getFilename();
}

and then when you want to print out your sorted vector of demos, you
can write code that actually writes out the Demos:

for(iter i = v.begin(); i != v.end(); i++)
{
cout << *i << endl;
}

or better yet, use an algorithm and write even less yourself:

std::copy(v.begin(), v.end(), ostream_iterator<Demo>(cout, "\n"));


Dave Moore
Jul 23 '05 #5

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

Similar topics

15
by: David Jones | last post by:
Hi I have a list of values stored in a vector e.g. std::vector<int> x; x = 1; x = 4; x = 2; x = 4;
6
by: John Black | last post by:
I have a sort statement for vectr like this, sort(vec.begin(), vec.end(), EleSmaller); in running I find that the sort procedure falls into an endless loop, by adding some debug statement I...
3
by: A_StClaire_ | last post by:
hi, not sure what I'm doing wrong here. getting "error C2064: term does not evaluate to a function taking 2 arguments" in response to my SortCardVector function...? Card.h: #pragma once
10
by: eiji | last post by:
Hi folks, I have a problem compiling this under VC6! Maybe someone has some minutes to look at this: template<class T> class Compare { public: Compare(){}; virtual ~Compare(){};
8
by: markww | last post by:
Hi, If I have a vector of structs like this: struct IMAGE { unsigned char *pPix; string strName; int nNumber; };
0
by: acosgaya | last post by:
hi, I am working in this problem, where I have a set of N d-dimensional points, e.g. (4,5,6,8) (2,0,4,6), are 4-d points, which I have stored in a vector of vectors. I am trying to partition...
6
by: Matt Chwastek | last post by:
Anyone who can help, I am curretnly attempting to write some code that will allow iteration using a vector<intfrom the highest possilbe degree of a combination of ones & zeros (111, 110, 101,...
3
by: Eric Lilja | last post by:
Hello, consider the following assignment and my code for it: /* Write a program that does the following: * Integer numbers shall be read from a textfile and stored in a std::vector. The name...
5
by: jeremit0 | last post by:
I'm trying to sort a vector<complex<double and can't figure it out. I recognize the problem is that there isn't a default operator< for complex data types. I have written my own operator and can...
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.