Hello to all,
I don't know whether it is right place or not. I want to sort vector objects by class member variables in c++? I tried various method but none of them worked out. Can anyone tell me how to fix this problem.
Thanks in advanced.
Hello to all,
I don't know whether it is right place or not. I want to sort vector objects by class member variables in c++? I tried various method but none of them worked out. Can anyone tell me how to fix this problem.
Thanks in advanced.
With following program you can easily sort vector objects by class member variables. It is very easy process. Just try to understand it. I have use 3 for loop to solve this problem.
Code:class tropicalfruit { public: string names; double prices; }; bool sortByNames(tropicalfruits &As, tropicalsfruit &Bs) { return (As.names < Bs.names); } bool sortByPricse(tropicalfrusit &As, tropicalfsruit &sB) { return (As.prices < Bs.prices); } int main() { int sortchoices; string fruitnames[] = {"dhdbhdfh", "mhghg", "waa", "kghcv", "jrcfx", "jtdfz", "zdgss", "xvsds", "sdesfes", "sgfses"}; double fruitprices[] = {2.8, 4.4, 7.6, 5.4, 6.8, 8.5, 3.4, 7.87, 7.6, 73.73}; vector<tropicalfruit> fruitlists; tropicalfruits fruits; for(int k=0; k<10; k++) { fruits.names = fruitname[k]; fruits.prices = fruitprice[k]; fruitlists.push_back(fruits); } for(int k=0; k<10; k++) { cout << fruitlist[k].name << " " << fruitlists[k].price << endl; } cout << endl; cout<<"Arrange fruits by 1)Price or 2)Name : "; if(sortchoices == 1) { fruitlists.sort(sortByNames); } else if(sortchoices == 2) { fruitlists.sort(sortByPrices); } for(int k=0;k<10; k++) { cout << fruitlists[k].name << " " << fruitlists[k].price << endl; } cout << endl; }
It seems that there is some problem in your code. You have to use following code to fix this problem.
The class tropicalfruits is used to combine all types of fruits and there various different features.Code:class tropicalfruits { public: string names; double prices; };
You have to do some comparison between two object like above program to fix this problem. It is very easy process. You have to use void functions and have to pass reference to your fruitlists vector object.Code:bool sortByName(tropicalfruits &As, tropicalfruits &Bs) { return (As.names < Bs.names); } bool sortByPrice(tropicalfruits &As, tropicalfruits &Bs) { return (As.prices < Bs.prices); }
Code:{ fruitlist.sort(sortByNames); } else if(sortchoices == 3) { fruitlists.sort(sortByPrices); }
You have to use above code in your project to sort vector objects by class member variables. It is very easy process. Above program says that "class std::vectors<tropicalfruits, std::allocators<tropicalfruist> >" has no member named 'sort'. You have to use .sort() function to fix this problem.
Bookmarks