1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Product {
public:
int ID;
string name;
string price;
Product(int myId, string MyProduct, string myPrice) : ID(myId), name(MyProduct), price(myPrice) {}
};
bool sortId(const Product &val1, const Product &val2) { return val1.ID < val2.ID; }
int main(){
// our Vector
vector<Product> MyProducts;
// populate some data in a random order of id
MyProducts.push_back(Product(9, "Toy", "11.22"));
MyProducts.push_back(Product(8, "Book", "22.33"));
MyProducts.push_back(Product(5, "Dress", "33.44"));
MyProducts.push_back(Product(7, "Car", "1116.22"));
MyProducts.push_back(Product(6, "Bike", "148.33"));
MyProducts.push_back(Product(2, "Phone", "99.44"));
MyProducts.push_back(Product(1, "Calculator", "19.22"));
MyProducts.push_back(Product(3, "Pen", "1.44"));
MyProducts.push_back(Product(4, "Blu-Ray", "199.44"));
// display list before sorting.
cout << endl << "*** Before Sorting ***" << endl;
for (int i = 0; i < 9; i++)
cout << "ID: " << MyProducts[i].ID << ", Name: " << MyProducts[i].name << ", Price: $" << MyProducts[i].price << endl;
// sort the list in ID order.
sort(MyProducts.begin(), MyProducts.end(), sortId);
cout << endl << "*** After Sorting ***" << endl;
for (int i = 0; i < 9; i++)
cout << "ID: " << MyProducts[i].ID << ", Name: " << MyProducts[i].name << ", Price: $" << MyProducts[i].price << endl;
return 0;
}
|