STL喜欢容器typedef快捷方式?

sho*_*osh 1 c++ stl

STL容器的常见模式是:

map<Key, Value> map;
for(map<Key, Value>::iterator iter = map.begin(); iter != map.end(); ++iter)
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

因此,为了避免编写模板参数的声明,我们可以在某处执行此操作:

typedef map<Key, Value> TNiceNameForAMap;
Run Code Online (Sandbox Code Playgroud)

但是,如果此映射仅用于单个函数或单个迭代,则这是一个烦人的开销.

这种typedef有什么方法吗?

Ste*_*sop 10

不确定你的意思是"开销".如果它简化了编写代码的方式,请使用它,否则坚持使用.

如果它仅在受限范围内使用,请将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;
}
Run Code Online (Sandbox Code Playgroud)

结合Ferruccio的建议(如果你正在使用boost),循环变为:

BOOST_FOREACH(DeDuplicator::pair p, everything) {
    total += p.second.size();
}
Run Code Online (Sandbox Code Playgroud)

并结合bk1e的建议(如果您正在使用C++ 0x或具有来自它的功能),并假设BOOST_FOREACH以我认为应该基于以下事实与auto交互:它通常可以处理对兼容类型的隐式转换:

std::map<Key, Value> everything;
// snipped code to run around...
int total = 0;
BOOST_FOREACH(auto p, everything) {
    total += p.second.size();
}
Run Code Online (Sandbox Code Playgroud)

不错.


Fer*_*cio 5

您可以使用Boost.Foreach