Hey guys! I was wondering if anybody could help me out with my C++ programming.

I'm currently trying to sort out a vector of class objects by their member variable but i dont know what i'm doing wrong or missing.

I googled alot of things and read through alot of examples on many websites but i always have some kind of problem applying them to my own code.

So here is my code:

class tropicalfruit //Class tropicalfruit
{
    public:
    string name;
    double price;
};

bool sortByName(tropicalfruit &A, tropicalfruit &B) //function to sort fruits by names
{
    return (A.name < B.name);
}

bool sortByPrice(tropicalfruit &A, tropicalfruit &B) //function to sort fruits by price
{
    return (A.price < B.price);
}

int main()
{
    int sortchoice;

    /*sample fruit names and prices*/
    string fruitname[] = {"avocado", "Watermelon", "Mango", "Pineapple", "Apple", "Orange", "Honeydew", "Pear", "Banana", "Durian"};
    double fruitprice[] = {0.8, 4.8, 0.6, 2.4, 0.4, 0.3, 3.1, 0.7, 3.5, 3.8};

    vector<tropicalfruit> fruitlist; //vector used to store tropicalfruit class objects
    tropicalfruit fruit; //tropicalfruit class object

    for(int i=0; i<10; i++) /*puts 10 objects with name and price into vector*/
    {
        fruit.name = fruitname[i];
        fruit.price = fruitprice[i];

        fruitlist.push_back(fruit);
    }

    for(int i=0; i<10; i++) /*displays all fruits' names and prices*/
    {
        cout << fruitlist[i].name << " " << fruitlist[i].price << endl;
    }
    cout << endl;

    cout<<"Arrange fruits by 1)Name or 2)Price : "; //asks user whether to sort by name or price
    cin>>sortchoice;
    if(sortchoice == 1)
    {
        fruitlist.sort(sortByName); //sort fruits by name
    }
    else if(sortchoice == 2)
    {
        fruitlist.sort(sortByPrice); //sort fruits by price
    }

    for(int i=0; i<10; i++) /*displays sorted fruits*/
    {
        cout << fruitlist[i].name << " " << fruitlist[i].price << endl;
    }
    cout << endl;
}

I know it looks abit different from any example but i thought that working on my original code was better than working on a code that has bits and pieces of whatever i found on the web :)

the 2 "bool ...." functions were what i saw from my friend's code.
he was able to sort the fruits out but he used a list of objects not a vector of objects. So i actually wanna know how i can sort a vector of objects (as simple as possible).

Recommended Answers

All 33 Replies

Your information is a little vague. Are you getting compiler errors or is the program simply not behaving as intended?

Regardless, these are my thoughts:

class tropicalfruit //Class tropicalfruit
{
    public:
    string name;
    double price;
};

This isn't a bad idea. Using public data members is not generally recommended practice so it could be better implemented, but for your situation it's probably fine. That's all I'll say. Let the others debate about the issue elsewhere if they choose.

bool sortByName(tropicalfruit &A, tropicalfruit &B) //function to sort fruits by names
{
    return (A.name < B.name);
}

bool sortByPrice(tropicalfruit &A, tropicalfruit &B) //function to sort fruits by price
{
    return (A.price < B.price);
}

As written, these really aren't much use, you'd get better results out of just putting the comparisons right in the code. To make better use of these, you'd be better off making them void functions and passing in a reference to your fruitlist vector. You would then implement the actual sort within the functions. Your vector is small enough, a simple bubble sort will work plenty well (if not familiar, google it). If you're familiar with the switch construct, you could create a single sort() function then pass the information in along with a byName/byPrice selection flag.

/*sample fruit names and prices*/
    string fruitname[] = {"avocado", "Watermelon", "Mango", "Pineapple", "Apple", "Orange", "Honeydew", "Pear", "Banana", "Durian"};
    double fruitprice[] = {0.8, 4.8, 0.6, 2.4, 0.4, 0.3, 3.1, 0.7, 3.5, 3.8};

    vector<tropicalfruit> fruitlist; //vector used to store tropicalfruit class objects
    tropicalfruit fruit; //tropicalfruit class object

    for(int i=0; i<10; i++) /*puts 10 objects with name and price into vector*/
    {
        fruit.name = fruitname[i];
        fruit.price = fruitprice[i];

        fruitlist.push_back(fruit);
    }

I'm not too sure if this is the most efficient method, but it seems to work. I would be cautious about the size/limits of my vector though. I'm not sure if push_back() has bounds checking and/or automatically resizes the vector to fit or not.

cout<<"Arrange fruits by 1)Name or 2)Price : "; //asks user whether to sort by name or price
    cin>>sortchoice;
    if(sortchoice == 1)
    {
        fruitlist.sort(sortByName); //sort fruits by name
    }
    else if(sortchoice == 2)
    {
        fruitlist.sort(sortByPrice); //sort fruits by price
    }

I would be surprised if this compiles. You are not calling sortByPrice() and sortByName() correctly. You need to take a closer look at how to define, and call, custom functions. This is a decent idea, but is not implemented correctly.

for(int i=0; i<10; i++) /*displays all fruits' names and prices*/
    {
        cout << fruitlist[i].name << " " << fruitlist[i].price << endl;
    }
    cout << endl;

This is a nice output loop. The issue is that you have 2 identical versions within your program. I'd suggest making this into a function such as displayFruitList(). You would then call the function whenever you want to output your list of fruits.

I hope that helps at least a little...

A vector doesn't have a sort method. You need

std::sort(fruitlist.begin(), fruitlist.end(), sortByName)

Do not forget to #include <algorithm>

yes i have problems compiling this part

{
fruitlist.sort(sortByName); //sort fruits by name
}
else if(sortchoice == 2)
{
fruitlist.sort(sortByPrice); //sort fruits by price
}

it says that "class std::vector<tropicalfruit, std::allocator<tropicalfruit> >" has no member named 'sort' "

I'm not sure how to go about using the sort() for vector even after reading many examples.

I can sort them perfectly fine using bubble sort or any other sort but my teacher said that its better for me to learn how to sort using the .sort() function instead but he never told me how to use it.

I edited my code a little:

class tropicalfruit //Class tropicalfruit
{
    public:
    string name;
    double price;
};

template<typename T1, typename T2>
bool sortByName(T1 &A, T2 &B) //function to sort fruits by names
{
    return (A.name < B.name);
}

void displayFruits(tropicalfruit fruitlist[])
{
    for(int i=0; i<10; i++)
    {
        cout << fruitlist[i].name << " " << fruitlist[i].price << endl;
    }
    cout << endl;
}

int main()
{
    //int sortchoice;

    /*sample fruit names and prices*/
    string fruitname[] = {"avocado", "Watermelon", "Mango", "Pineapple", "Apple", "Orange", "Honeydew", "Pear", "Banana", "Durian"};
    double fruitprice[] = {0.8, 4.8, 0.6, 2.4, 0.4, 0.3, 3.1, 0.7, 3.5, 3.8};

    vector<tropicalfruit> fruitlist; //vector used to store tropicalfruit class objects
    tropicalfruit fruit; //tropicalfruit class object

    for(int i=0; i<10; i++) /*puts 10 objects with name and price into vector*/
    {
        fruit.name = fruitname[i];
        fruit.price = fruitprice[i];

        fruitlist.push_back(fruit);
    }

    displayFruits(fruitlist);

    std::sort(fruitlist.begin(), fruitlist.end(), sortByName);

    displayFruits(fruitlist);
}

but it doesnt compile. it has problems at the displayfruit(fruitlist) function and the std::sort(....) in the main() function

tried copying exactly how it was in the cplusplus.com website

class tropicalfruit //Class tropicalfruit
{
    public:
    string name;
    double price;

    bool operator()(tropicalfruit &A ,tropicalfruit &B)
    {
        return A.name < B.name;
    }
};

bool sortByName(tropicalfruit &A, tropicalfruit &B) //function to sort fruits by names
{
    return (A.name < B.name);
}

void displayFruits(tropicalfruit fruitlist[])
{
    for(int i=0; i<10; i++)
    {
        cout << fruitlist[i].name << " " << fruitlist[i].price << endl;
    }
    cout << endl;
}

int main()
{
    /*sample fruit names and prices*/
    string fruitname[] = {"avocado", "Watermelon", "Mango", "Pineapple", "Apple", "Orange", "Honeydew", "Pear", "Banana", "Durian"};
    double fruitprice[] = {0.8, 4.8, 0.6, 2.4, 0.4, 0.3, 3.1, 0.7, 3.5, 3.8};

    vector<tropicalfruit> fruitlist; //vector used to store tropicalfruit class objects
    tropicalfruit fruit; //tropicalfruit class object

    for(int i=0; i<10; i++) /*puts 10 objects with name and price into vector*/
    {
        fruit.name = fruitname[i];
        fruit.price = fruitprice[i];

        fruitlist.push_back(fruit);
    }

    displayFruits(fruitlist);

    sort (fruitlist.begin(), fruitlist.end(), sortByName);

    displayFruits(fruitlist);
}

but the compiler gives me rubbish when i try to compile this.

First, you need to show us your #includes, if you have any. Almost everything you do relies on the presence of a specific header. For example, for a vector to work, you must #include <vector> . Without it, you have nothing. My guess is you probably forgot to #include the proper header for .sort().

Second, you didn't create your iterators correctly. As a result, .sort() doesn't know what you are sending it. See the example here:
http://www.cplusplus.com/reference/stl/vector/begin/

Third, your display function doesn't like the argument you are sending it because the datatypes don't match. You're sending it a vector, but you're telling it to look for an array. Vectors and arrays are similar, but they are not the same. You will have to revise your function definition to fit the data.

#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <list>
#include <iterator>
#include <vector>
#include <stack>
#include <queue>

these are what i've included. sorry i'm not well versed in all this computer science language and things so i really dont understand about half the things u say.

I think i've have enough of this nonsense of trying to use sort() and crack my head and all... i'm just going with the bubble sort. thanks alot for all your help people :D

I think i've have enough of this nonsense of trying to use sort() and crack my head and all... i'm just going with the bubble sort. thanks alot for all your help people :D

Don't give up now!!
Take a look at this thread:
http://www.daniweb.com/forums/thread242984.html#post1064721

It should explain all you need to know about using std::sort with a vector.

Cheers for now.
Jas.

What exactly is "rubbish"? Please be more detailed, we can't see what you see. I suspect one of the errors is related to your overload function for operator() on line 7. When you overload an operator, you need to be sure you tell it the correct operator. It should be operator[b]<[/b] not operator().

What term(s) are you not understanding? Perhaps we can clarify something for you.

[soapbox]
Also, I think there is another issue at work here. Let's take this back to square-1. It seems that part of the issue is that you are trying to compare yourself to "your friend". It seems you're trying to duplicate his code without knowing what it's doing or how it works. That is a big no-no, it will only lead to much more confusion and frustration down the road because you aren't absorbing the concept(s). When you do that, you just barf out something that you really don't know what it is, but it works and gets you a grade. Is he fairly experienced? How long have you been studying programming? If there's much discrepancy, you're in for a lot of headaches. I'm one of the more experienced in my classes. I can tell you from experience, it's very annoying when your neighbors in the lab keep craning their necks to peek at your code. I don't mind helping out if asked, but don't try to copy then say "WTF! there's no way that'll work" or "how the hades does that work?". Think it through then describe your thoughts to the computer. It's really no different than having a conversation with another individual, you're just speaking C++ instead of your native language.
[/soapbox]

well i saw my friend's code and i thought his method would work but i realized it doesnt because he used a list to store his objects while i used a vector and i realised i couldnt get it right like he did with his way of sorting things. but at the same time i dont really know WHY it is like that. i've been studying C++ for nearly 6 months now. My friend is as experienced as me but i get better grades. The only problem is that when i'm asked to do something i dont know of like using sort() when i dont have a clue how it is used and the syntax and everything for it i get lots of problems and screw things up to the max.

And my teacher NEVER taught us the syntax and procedures to using sort() and under what circumstances we can/cannot use it. he just said "google it" and learn how to use sort().

class tropical //Class tropical
{
    public:
    string name;
    int price;
};

bool sortByName(tropical &t1, tropical  &t2); //function declaration or intialisation or wadever...

void displayfruits(vector<tropical> fruitlist) //function that displays objects in vector
{
    for(int i=0;i<10;i++) /*displays all fruits' names and prices*/
    {
        cout << fruitlist[i].name << "  \t" << fruitlist[i].price << endl;
    }
    cout << endl;
}

int main()
{
    int sortchoice; //variable used in switch-case to select sorting method

    /*sample fruit names and prices*/
    string fruitname[] = {"Avocado", "Papaya", "Grapefruit", "Pineapple", "Jackfruit", "Orange", "Honeydew", "Mangosteen", "Banana", "Durian"};
    int fruitprice[] = {1, 4, 6, 2, 10, 3, 9, 7, 5, 8};

    vector<tropical> fruitlist; //vector used to store tropicalfruit class objects
    tropical fruit; //tropicalfruit class object

    for(int i=0; i<10; i++) /*puts 10 objects with name and price into vector*/
    {
        fruit.name = fruitname[i];
        fruit.price = fruitprice[i];

        fruitlist.push_back(fruit);
    }

    cout << "Name \t\tPrice" << endl << "==========\t=====" << endl;

    displayfruits(fruitlist); //displays objects in fruitlist vector

    cout<<"Arrange fruits by 1)Name or 2)Price : "; //asks user whether to sort by name or price
    cin>>sortchoice;
    if(sortchoice == 1)
    {
        sort (fruitlist.begin(), fruitlist.end(), sortByName); //sorts fruit objects by their names
        //problem!! gives me rubbish errors when compiled
        //could it be compiler problems?? I'm using Code::Blocks 8.02.. dont know what compiler
    }

    else if(sortchoice == 2)
    {
        //function to sort fruit objects by price
    }

    displayfruits(fruitlist); //displays objects in fruitlist vector

    cout << endl;
}

bool sortByName(tropical &t1, tropical  &t2)
{
    return t1.name < t2.name;
}

Thanks Jason, i found out how to pass a vector into the function :D

and check out my code. i did almost exactly as the program in the other thread but my compiler still gives me rubbish... and rubbish meaning it loads this "stl_algo.h" and points me to these few lines

if (__comp(__a, __b))
	if (__comp(__b, __c))
	  return __b;
	else if (__comp(__a, __c))
	  return __c;
	else
	  return __a;
      else if (__comp(__a, __c))
	return __a;
      else if (__comp(__b, __c))
	return __c;
      else
	return __b;

i dont know what that means.

Ok, now we're getting somewhere...

If the instructor wants you to use sort(), you will have to look at the information about iterators that I linked for you. The sort() function requires a beginning and an ending iterator. Once you figure those out, you can move on to the required comparison function.

Do you have a textbook? Can you find any information on sort and iterators in the index?

EDIT:
I understand you have lots to say, but you gotta stop the double posts, it's very confusing... I'm afraid I can't help you with the second post.

I dont understand why the program in the link that Jason just provided works but mine does not even though both are so similar.

This is great... i just ran the other program in the link and it gives the same problem too... i seriously believe its compiler problems although i've no evidence to confirm it.

Are you referencing the std namespace? You need to reference the std namespace to access cin, cout, endl, sort, and several other things. I don't see that anywhere in your posted code.

#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <list>
#include <iterator>
#include <vector>
#include <stack>
#include <queue>
#include <string>

using namespace std;

class tropical //Class tropical
{
    public:
    string name;
    int price;
};

bool sortByName(tropical &t1, tropical  &t2); //function declaration or intialisation or wadever...

void displayfruits(vector<tropical> fruitlist) //function that displays objects in vector
{
    cout << "Name \t\tPrice" << endl << "==========\t=====" << endl;
    for(int i=0;i<10;i++) //displays all fruits' names and prices
    {
        cout << fruitlist[i].name << "  \t" << fruitlist[i].price << endl;
    }
    cout << endl;
}

int main()
{
    int sortchoice; //variable used to select sorting method
    string searchfruit; //variable used to store input from user to search for fruit

    //sample fruit names and prices
    string fruitname[] = {"Avocado", "Papaya", "Grapefruit", "Pineapple", "Jackfruit", "Orange", "Honeydew", "Mangosteen", "Banana", "Durian"};
    int fruitprice[] = {1, 4, 6, 2, 10, 3, 9, 7, 5, 8};

    vector<tropical> fruitlist; //vector used to store tropicalfruit class objects
    tropical fruit; //tropicalfruit class object
    vector<tropical>::iterator it; //all-purpose RandomAccessIterator

    for(int i=0; i<10; i++) //puts 10 objects with name and price into vector
    {
        fruit.name = fruitname[i];
        fruit.price = fruitprice[i];

        fruitlist.push_back(fruit);
    }

    displayfruits(fruitlist); //displays objects in fruitlist vector

    cout<<"Arrange fruits by 1)Name or 2)Price : "; //asks user whether to sort by name or price
    cin>>sortchoice;
    if(sortchoice == 1)
    {
        sort (fruitlist.begin(), fruitlist.end(), sortByName); //sorts fruit objects by their names
        //problem!! gives me rubbish errors when compiled. could it be compiler problem??
    }
    else if(sortchoice == 2)
    {
        //function to sort fruit objects by price
    }
    
    displayfruits(fruitlist); //displays objects in fruitlist vector
}

bool sortByName(tropical &t1, tropical &t2)
{
    return t1.name < t2.name;
}

that's my full program :D

It must be something with your compiler or your libraries. It just compiled fine for me in MS-VC++ 2008 it also ran fine on the name sort. You still have to add the price sort though.

I concur, that last bit of code you posted works fine in VS2008.

But I'll take a look at it with Code::Blocks tonight on my linux box to see whether that works too.

Which compiler/IDE are you using?

Most of the code is pretty much untouched, I've left the OP's comments in the code. The only real difference is, the following code compiles and runs without any errors. (in VS2008 at least!)

Mine was VS2008 as well, but it compiled without any modification at all... No warnings or anything... Strange... I wonder if the STL libraries that he's using are borked...

Could it be an issue with C vs. C++? I'm inclined to say no because I doubt he'd have gotten this far if it was. Roger, what is the name of your source file? Is it *.c or *.cpp?

I'm beginning to suspect that perhaps the OP is using an older compiler which doesn't support the standard library particularly well.

bool sortByName(tropical &t1, tropical  &t2);

sort (fruitlist.begin(), fruitlist.end(), sortByName);
//problem!! gives me rubbish errors when compiled. could it be compiler problem??

GCC 4.4.0 says; stl_algo.h:124: error: invalid initialization of reference of type 'tropical&' from expression of type 'const tropical' meaning that you need to change to:

bool sortByName(const tropical &t1, const tropical  &t2);

With regard to this, when trying out the example snippets found on e.g. internet, be prepared that they may be outdated i.e. a relatively recent/standards-compliant compiler will reject the code while others happily compile without a hitch.

With regard to this, when trying out the example snippets found on e.g. internet, be prepared that they may be outdated i.e. a relatively recent/standards-compliant compiler will reject the code while others happily compile without a hitch

This is a true statement, you must keep it in mind. However, when you consider that VC++2008 is standards-compliant and that 2 of us have successfully compiled it with VS2008, the opposite seems to be the situation here. It appears that he's attempting to compile modern code with an outdated compiler.

However, when you consider that VC++2008 is standards-compliant and that 2 of us have successfully compiled it with VS2008, the opposite seems to be the situation here. It appears that he's attempting to compile modern code with an outdated compiler.

In this particular case, VS 2008 is the one that is more 'relaxed'. One good place to figure out whether a given piece of code really is standards-compliant, is Comeau's online service. You can check it out at Test Drive Comeau C++ Online.

In this particular case, VS 2008 is the one that is more 'relaxed'. One good place to figure out whether a given piece of code really is standards-compliant, is Comeau's online service. You can check it out at Test Drive Comeau C++ Online.

Yeah, that's true, the MS compilers have never adhered strictly to the standard. As far as I understand it, VS2008 is standards compliant, but I think you have to alter the settings somewhere to make it stick more strictly to the standard. Otherwise by default it is a little looser and will allow things that perhaps other compilers like gcc will reject.. I hadn't taken that into consideration. If the OP is using a more strict compiler, then that could also explain the problems he was having.

{EDIT:} Actually, after messing with VS2008's compiler options, I can't actually get the compiler to throw a warning or an error about the lack of const in the comparison function....So maybe I was wrong, it's just not standards compliant after all!

Jas.

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

using namespace std;

class tropical //Class tropical
{
    public:
    string name;
    int price;
};

bool sortByName(const tropical &t1,const tropical &t2) //comparison function to be used compare the names of 2 fruit objects
{
    return t1.name < t2.name;
}

bool sortByPrice(const tropical &p1,const tropical &p2) //comparison function to be used to compare the price of 2 fruit objects
{
    return p1.price < p2.price;
}

void displayfruits(vector<tropical> fruitlist) //function that displays objects in vector
{
    cout << "Name \t\tPrice" << endl << "==========\t=====" << endl;
    for(int i=0;i<10;i++)
    {
        cout << fruitlist[i].name << "  \t" << fruitlist[i].price << endl;
    }
    cout << endl;
}

int main()
{
    int sortchoice; //variable used to select sorting method
    string searchfruit; //variable used to store input from user to search for fruit

    //sample fruit names and prices
    string fruitname[] = {"Avocado", "Papaya", "Grapefruit", "Pineapple", "Jackfruit", "Orange", "Honeydew", "Mangosteen", "Banana", "Durian"};
    int fruitprice[] = {1, 4, 6, 2, 10, 3, 9, 7, 5, 8};

    vector<tropical> fruitlist; //vector used to store tropicalfruit class objects
    tropical fruit; //tropicalfruit class object
    vector<tropical>::iterator it; //all-purpose RandomAccessIterator

    for(int i=0; i<10; i++) //puts 10 objects with name and price into vector
    {
        fruit.name = fruitname[i];
        fruit.price = fruitprice[i];

        fruitlist.push_back(fruit);
    }

    displayfruits(fruitlist); //displays objects in fruitlist vector

    cout<<"Arrange fruits by 1)Name or 2)Price : "; //asks user whether to sort by name or price
    cin>>sortchoice;
    if(sortchoice == 1)
    {
        sort (fruitlist.begin(), fruitlist.end(), sortByName); //sorts fruit objects by their names
        //problem!! gives me rubbish errors when compiled. compiler/library problem??
    }
    else if(sortchoice == 2)
    {
        sort (fruitlist.begin(), fruitlist.end(), sortByPrice);//function to sort fruit objects by price
    }

    displayfruits(fruitlist); //displays objects in fruitlist vector
}

manage to get it up and running. dont know what's the problem with my compiler but check it out, i've to put a 'const' in front of my class type in the comparison functions

bool sortByName(const tropical &t1,const tropical &t2) //comparison function to be used compare the names of 2 fruit objects
{
    return t1.name < t2.name;
}

bool sortByPrice(const tropical &p1,const tropical &p2) //comparison function to be used to compare the price of 2 fruit objects
{
    return p1.price < p2.price;
}

:D

Yeah, that's true, the MS compilers have never adhered strictly to the standard. As far as I understand it, VS2008 is standards compliant, but I think you have to alter the settings somewhere to make it stick more strictly to the standard. Otherwise by default it is a little looser and will allow things that perhaps other compilers like gcc will reject.. I hadn't taken that into consideration. If the OP is using a more strict compiler, then that could also explain the problems he was having.

{EDIT:} Actually, after messing with VS2008's compiler options, I can't actually get the compiler to throw a warning or an error about the lack of const in the comparison function....So maybe I was wrong, it's just not standards compliant after all!

Jas.

According to Microsoft's documentation, if you set the language option "Disable Language Extensions" to "yes" it will force the compiler to follow ANSI standards.

When I did that, everything was still fine.

I do have a question though. Why would the const make a difference? I can see why you would want it, but unless there is something in a definition somewhere, it really shouldn't be necessary should it?

The name of my source code is main.cpp

I got my code::blocks and compiler and everything from my school two years ago, and never changed or upgraded anything until now.

But i'm so happy that i can finally do sort() for my programs!!
Another milestone achieved!

I've been having 3 projects that are still pending cuz i couldnt get the sorting function up and running lol. Now it's all solved! Yay!

Thanks for all your help and patience!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.