smart pointer containing class type

I have a customer class containing Name and Age. I am wrapping the customer class in a smart pointer and made a vector of the smart pointer.
I have taken 3 customers and pushed them into the vector. Now I want to show the customers details by using for_each algorithm. But I am not able to write the code for functor Display(). Can any body help. Given my code below.

class customer {
private:
int Age;
string Name;
public:
customer();
customer(int x, string y):Age(x),Name(y) {
}
~customer() {
cout << "Destructor of customer is called" << endl;
}
int getAge() const{
return Age;
}
string getName() const{
return Name;
}

};
template<typename T>
struct Display : unary_function< const T&, void> {
void operator()(const T& Obj)const {

}
};

typedef shared_ptr<customer> SmartCustomer;
int main() {
typedef vector<SmartCustomer> CustomerVect;
CustomerVect V1;
V1.reserve(10);
for(int i=0; i<3; i++) {
string Name;
int Age;
cout << "Name:";
cin >> Name;
cout << "Age:";
cin >> Age;
V1.push_back(SmartCustomer(new customer(Age,Name)));
cout << endl;
}
for_each(V1.begin(),V1.end(),Display<SmartCustomer>());
return 0;
}
Obj is a const SmartCustomer&, which is const std::shared_ptr<customer> &.

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
54
55
56
#include <string>
#include <algorithm>
#include <memory>
#include <vector>
#include <iostream>

using namespace std;

class customer {
private:
	int Age;
	string Name;
public:
	customer();
	customer(int x, string y):Age(x),Name(y) {
	}

	~customer() {
		cout << "Destructor of customer is called" << endl;
	}

	int getAge() const{
		return Age;
	}

	string getName() const{
		return Name;
	}
};

template<typename T>
struct Display : unary_function< const T&, void> {
	void operator()(const T& Obj)const {
		cout << Obj->getName() << " : " << Obj->getAge() << endl;
	}
};

typedef shared_ptr<customer> SmartCustomer;

int main() {
	typedef vector<SmartCustomer> CustomerVect;
	CustomerVect V1;
	V1.reserve(10);
	for(int i=0; i<3; i++) {
		string Name;
		int Age;
		cout << "Name:";
		cin >> Name;
		cout << "Age:";
		cin >> Age;
		V1.push_back(SmartCustomer(new customer(Age,Name)));
		cout << endl;
	}
	for_each(V1.begin(),V1.end(),Display<SmartCustomer>());
	return 0;
} 
Last edited on
Thanks. It was a silly mistake from my side for which my functor was giving compilation issue. Now corrected the issue by looking into your functor.
Topic archived. No new replies allowed.