STL 之类的容器 typedef 快捷方式? [英] STL like container typedef shortcut?

查看:36
本文介绍了STL 之类的容器 typedef 快捷方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

STL 容器的常见模式是这样的:

A common pattern with STL containers is this:

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

所以为了避免写模板参数的声明,我们可以在某处这样做:

So in order to avoid writing the declaration of the template parameters we can do this somewhere:

typedef map<Key, Value> TNiceNameForAMap;

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

But if this map is only used in a single function or for a single iteration this is an annoying overhead.

有没有办法绕过这个 typedef?

Is there any way around this typedef?

推荐答案

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

Not sure what you mean by "overhead". If it simplifies the way you write your code, use it, otherwise stick with the longhand.

如果只在受限范围内使用,请将 typedef 放在同一范围内.那么它就不需要发布、记录或出现在任何 UML 图表上.例如(我不认为这是其他方面最好的代码):

If it's only used in a restricted scope, put the typedef in that same scope. Then it doesn't need to be published, or documented, or appear on any UML diagrams. For example (and I don't claim this is the best code ever in other respects):

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;
}

结合 Ferruccio 的建议(如果您使用的是 boost),循环变为:

Combining with Ferruccio's suggestion (if you're using boost), the loop becomes:

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

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

And combining with bk1e's suggestion (if you're using C++0x or have features from it), and assuming that BOOST_FOREACH interacts with auto in the way I think it should based on the fact that it can normally handle implicit casts to compatible types:

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

还不错.

这篇关于STL 之类的容器 typedef 快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆