尝试内的C ++变量范围

赫里斯托·韦内夫

考虑以下代码:

try {
    const Asdf &a = map1.at(index1);
    const Bsdf &b = map2.at(index2);
} catch(std::out_of_range&) {
    return false;
}
// <code>
std::cout<<a[b[42]]; // May throw std::out_of_range which should not be caught here.
return true;

<code>使用a和b。我有两个选择:

  • 放入<code>try块
  • 在try块中获取指针,然后取消引用

第一个选项是错误的,因为如果<code>抛出std::out_of_range该函数将返回false,则仅当映射查找失败时才会发生。

第二种选择可能有点丑陋:

const Asdf *a;
const Bsdf *b;
try {
    a = &map1.at(index1); // What?
    b = &map2.at(index2);
} catch(std::out_of_range&) {
    return false;
}
std::cout << (*a)[(*b)[42]];
return true;

有没有更好的办法?Python中的try-except-else之类的东西会很好,但是C ++中不存在。

米格尔·马丁

无需进行任何异常处理。std::map::find,给定密钥,将为您提供迭代器。如果该元素在地图中不存在,find则将返回end迭代器(即map.end())。

当取消引用迭代器时,您将收到一对值。第一个是键,第二个是对象。

auto aIt = map1.find(index1);
auto bIt = map2.find(index2);

if(aIt == map1.end() || bIt == map2.end())
{
    return false;
}

const Asdf &a = aIt->second;
const Bsdf &b = bIt->second;

std::cout << a[b[42]];

return true;

请注意,C ++中的begin迭代器已定义为使得迭代器位于开始位置,并且end迭代器位于最后一个元素(http://en.cppreference.com/w/cpp/iterator/end的后面,即,容器是:[开始,结束)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章