Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Use Function Adapters to Extend Generic Algorithms' Usage-2 : Page 2

Step 1: Demonstrating the Problem
Suppose you want to write an OS service that iterates through each of the currently active tasks. First, you store the Task objects in a container class such as std::vector:

class Task { public: explicit Task(int id) : pid(id) {} void show_pid() const { std::cout << "pid: " << pid << std::endl; } //.. }; std::vector <Task> vt; //populate the vector vt.push_back(Task(1)); vt.push_back(Task(2)); vt.push_back(Task(3));

Figure 1: Here's the output for this for-loop:.

The tricky part is traversing the vector. You can use a for-loop for this purpose (as shown in Figure 1):

for (std::vector<Task>::const_iterator it=vt.begin(); it!=vt.end(); ++it) { it->show_pid(); //list every task's pid }

However, this solution is only suitable for simple cases. In real world applications, for-loops such as this could become a maintenance problem. If you decide to use a different container, say std::list, you'll have to modify the for-loop as well:

for (std::list<Task>::const_iterator it=vt.begin(); //...

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.