Re: Sorting data and creating multiple instances of the same class.
Daz wrote:
Daz wrote:
That's fantastic! Thanks for your help Rolf. You're a diamond!
Hello again.
I can't seem to get sort to work. I know I am missing something, and
probably not using the template properly, but I don't understand how. I
have tried at least 30 different things, and each time I just get more
errors.
The code below gives a single error:
void InitializeBBObjects()
{
std::vector<BBObject> objects;
typedef std::vector<BBObject>::iterator iterator;
iterator it = objects.begin(), end = objects.end();
objects.push_back(BBObject(BERRY,50,99,65,"Berry"));
objects.push_back(BBObject(FOOD,10,159,45,"Fries"));
objects.push_back(BBObject(FOOD,4,76,23,"Hamburger"));
Not a good idea. Adding objects to your vector invalidates all iterators
into that vector, so you should create the iterators after your push_back.
std::sort<iterator>(*it, *end); // <-- This is whre the error lies.
std::sort wants iterators, not the objects they point to, so don't use the
dereference operator. Just use:
std::sort(it, end);
or directly:
std::sort(objects.begin(), objects.end());
However, it still won't work that way, because sort needs a way to compare
two objects, and by default it uses operator< for that, which isn't defined
for your objects. Since you want to sort by different elements, you need to
write your own comparison function that compares two objects by the member
you want to sort by.
}
The above is basically a simple test script to help me try to figure
out how to do a sort. I have used sort before on a list of ints, but I
don't have any idea what I need to change in order to make it work with
a list of my objects.
Any more input would be appreciated (sorry Rolf) :(
You're welcome. A good book about C++ should explain that all. You should
consider getting one. IIRC, the FAQ to this newsgroup contains a list of
candidates.