Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

6.9. Storing Containers in Containers

Problem

You have a number of instances of a standard container (lists, sets, etc.), and you want to keep track of them by storing them in yet another container.

Solution

Store pointers to your containers in a single, master container. For example, you can use a map to store a string key and a pointer to a set as its value. Example 6-12 presents a simple transaction log class that stores its data as a map of string-set pointer pairs.

Example 6-12. Storing set pointers in a map

#include <iostream> #include <set> #include <map> #include <string> using namespace std; typedef set<string> SetStr; typedef map<string, SetStr*> MapStrSetStr; // Dummy database class class DBConn { public: void beginTxn() {} void endTxn() {} void execSql(string& sql) {} }; class SimpleTxnLog { public: SimpleTxnLog() {} ~SimpleTxnLog() {purge();} // Add an SQL statement to the list void addTxn(const string& id, const string& sql) { SetStr* pSet = log_[id]; // This creates the entry for if (pSet == NULL) { // this id if it isn't there pSet = new SetStr(); log_[id] = pSet; } pSet->insert(sql); } // Apply the SQL statements to the database, one transaction // at a time void apply() { for (MapStrSetStr::iterator p = log_.begin(); p != log_.end(); ++p) { conn_->beginTxn(); // Remember that a map iterator actually refers to an object // of pair<Key,Val>. The set pointer is stored in p->second. for (SetStr::iterator pSql = p->second->begin(); pSql != p->second->end(); ++pSql) { string ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page