Sort and find Object in Container Vector



/*
 * session11.cpp
 *
 *  Created on: Aug 11, 2013
 *      Author: kobee
 */

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <stdio.h>
#include <sstream>
#include <iomanip>

using namespace std;

class Product{
	string id;
	string name;
	float price;

public:
	Product(){
		id = "no-id";
		name = "no-name";
		price = 0.0f;
	};

	Product(string id, string name, float price){
		this->id = id;
		this->name = name;
		this->price = price;
	};

	string getId();
	string getName();
	float getPrice();

	string toString(){
		ostringstream convert;
		convert << price;

		string value = "";
		value += "Product[ID = "+ id + " Name= " + name +" Price= " + convert.str() +"]";
		return value;
	}

};

string Product::getId(){
	return id;
}
string Product::getName(){
	return name;
}
float Product::getPrice(){
	return price;
}

// to sort and find
bool operator<(Product p1, Product p2){
	return p1.getId() < p2.getId();
}

bool operator==(Product p1, Product p2){
	return p1.getId() == p2.getId();
}

int main(){
	vector<Product> productList;

	productList.push_back(Product("ID004","Vitamin",4000.0f));
	productList.push_back(Product("ID003","Iphone4",3000.0f));
	productList.push_back(Product("ID001","HTC One",1000.0f));
	productList.push_back(Product("ID002","NotePad",2000.0f));

	cout << "Products List : \n";
	vector<Product>::iterator iter;
	for(iter = productList.begin(); iter != productList.end(); iter++){
		cout << iter->toString() << endl;
	}

	cout << "\nProducts List Sorted : \n";
	//sort() algorithm base on This requires that operator<().
	// Sort on ID's Product
	sort(productList.begin(),productList.end());

	for(iter = productList.begin(); iter != productList.end(); iter++){
		cout << iter->toString() << endl;
	}

	cout << "\nFind Product with ID = ID002 : \n";
	//find() algorithm This requires that operator==()
	iter = find(productList.begin(), productList.end(), Product("ID002","",0.0f));

	cout << "Product found is => " << iter->toString();

	return 0;
}

Result :

d1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: