c++ - STL like container typedef shortcut? -


a common pattern stl containers this:

map<key, value> map; for(map<key, value>::iterator iter = map.begin(); iter != map.end(); ++iter) {   ... } 

so in order avoid writing declaration of template parameters can somewhere:

typedef map<key, value> tnicenameforamap; 

but if map used in single function or single iteration annoying overhead.

is there way around typedef?

not sure mean "overhead". if simplifies way write code, use it, otherwise stick longhand.

if it's used in restricted scope, put typedef in same scope. doesn't need published, or documented, or appear on uml diagrams. example (and don't claim best code ever in other respects):

int totalsize() {     typedef std::map<key, value> deduplicator;     deduplicator everything;      // run around universe finding everything. if encounter key     // more once it's added once.      // compute total     int total = 0;     for(deduplicator::iterator = everything.begin(); <= everything.end(); ++i) {         total += i->second.size(); // yeah, yeah, overflow. whatever.     }     return total; } 

combining ferruccio's suggestion (if you're using boost), loop becomes:

boost_foreach(deduplicator::pair p, everything) {     total += p.second.size(); } 

and combining bk1e's suggestion (if you're using c++0x or have features it), , assuming boost_foreach interacts auto in way think should based on fact can handle implicit casts compatible types:

std::map<key, value> everything; // snipped code run around... int total = 0; boost_foreach(auto p, everything) {     total += p.second.size(); } 

not bad.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -