[ create a new paste ] login | about

Link: http://codepad.org/KRIjAhrL    [ raw code | output | fork ]

C++, pasted on Jul 31:
#include<vector>
#include<algorithm>
#include<iostream>
#include<functional>

using namespace std;

#define SAFE_DELETE(p)  { if(p) { delete (p);     (p)=NULL; } }
#define SAFE_DELETE_ARRAY(p)  { if(p) { delete[] (p);     (p)=NULL; } }

class A;

struct findName{
	const char* target_;
public:
	findName(const char* name):target_(name){}
	template<typename T>
	bool operator()(T *pObject ) {
		return strcmp( target_, pObject->getName() )==0;
	}
	template<typename T>
	friend typename T::iterator operator|(T &source, findName f)
	{
		return find_if(source.begin(), source.end(), f);
	}
};

struct Deleter{
	template<typename T>
	void operator()(const T* ptr) const
	{
		SAFE_DELETE(ptr);
	}
};


class A {
public:
	A(const char *pName) {
		int strSize= strlen(pName);
		name_=new char[strSize+1];
		strcpy(name_, pName);
	}
	virtual ~A()
	{
		SAFE_DELETE_ARRAY(name_);
	}
	const char* getName(){
		return name_;
	}
private:
	char* name_;
};
int main(){
	vector<A*> array;
	A *p = new A("test");
	array.push_back(p);

	std::vector<A*>::iterator it=find_if(array.begin(), array.end(), findName("test") );
	cout << (*it)->getName() << endl;

	it=array|findName("test");
	cout << (*it)->getName() << endl;

	std::for_each(array.begin(), array.end(), Deleter() );
	return 0;
}


Output:
1
2
test
test


Create a new paste based on this one


Comments: