dcsimg
Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


advertisement
 

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


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date