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 ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.