不确定您的意思是“开销”。如果它简化了你写代码的方式,使用它,否则坚持使用longhand。
如果它仅用于受限制的范围,则将typedef放在同一范围内。然后,它不需要发布,记录或出现在任何UML图表上。例如(我不声称这是最好的代码曾经在其他方面):
int totalSize() {
typedef std::map<Key, Value> DeDuplicator;
DeDuplicator everything;
// Run around the universe finding everything. If we encounter a key
// more than once it's only added once.
// now compute the total
int total = 0;
for(DeDuplicator::iterator i = everything.begin(); i <= everything.end(); ++i) {
total += i->second.size(); // yeah, yeah, overflow. Whatever.
}
return total;
}
与费鲁乔的建议合并(如果你使用升压),循环变为:
BOOST_FOREACH(DeDuplicator::pair p, everything) {
total += p.second.size();
}
并结合bk1e的建议(如果您使用C++ 0x或具有它的功能),并假设BOOST_FOREACH与自动进行交互的方式,我认为它应该基于它可以正常处理隐式强制转换以兼容类型:
std::map<Key, Value> everything;
// snipped code to run around...
int total = 0;
BOOST_FOREACH(auto p, everything) {
total += p.second.size();
}
不错。
干得好!您的最后一个符合*和*可读性的Python级别。 – rlerallut 2008-09-25 22:41:19
甚至可能跑得更快。 – 2008-09-25 23:21:28