码迷,mamicode.com
首页 > 其他好文 > 详细

std::out_of_range异常

时间:2020-02-24 20:28:20      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:container   cout   camera   string   方式   cat   inf   spl   error:   

使用C++容器类访问成员时由于使用问题可能会遇到"terminate called after throwing an instance of ‘std::out_of_range‘"或者"Abort message: ‘terminating with uncaught exception of type std::out_of_range"。问题的大概意思是:访问越界了。没有捕获std::out_of_range类型的异常终止。

通常在使用vector、map这样的C++容器类型时会遇到,这里我们以map类型为例,加以说明。

std::out_of_range异常的描述

假设我们定义了一个map类型的变量g_mapIsDestroyedRefCount,要访问容器中的数据项有多种方式。例如,获取g_mapIsDestroyedRefCount中key值为cameraId的值,可以这样:

  1. g_mapIsDestroyedRefCount[cameraId]
  2. g_mapIsDestroyedRefCount.at(cameraId)

两种写法都可以获取key为cameraId的value,一般效果看不出来差别,但是当g_mapIsDestroyedRefCount中不存在key为cameraId的<key, value>时就会出现“std::out_of_range”访问越界问题。

导致std::out_of_range的原因

容器类型访问方法使用有问题

对于std::map::at官方声明:

  mapped_type& at (const key_type& k);
const mapped_type& at (const key_type& k) const;
对于std::map::at使用有如下说明:
Access element        访问元素

Returns a reference to the mapped value of the element identified with key k.      返回元素键为k的映射值的引用,即Key为k的元素的对应value值。
If k does not match the key of any element in the container, the function throws an out_of_range exception.   如果容器中没有匹配的k键,该函数将抛出一个out_of_range异常

如何避免std::out_of_range异常

  • 正确使用
  • 错误使用

1.std::map::at的正确使用

 

#include <iostream>
#include <string>
#include <map>

std::map<int, int> g_mapIsDestroyedRefCount;

int main()
{
    int cameraId = 1;
    cout << "Let‘s try"<< endl;
    
     //向map中添加测试数据 
    g_mapIsDestroyedRefCount.insert(std::pair<int, int>(0, 2))    cout << "cameraId:"<< cameraId<< "count:";
    try {
        cout<< g_mapIsDestroyedRefCount.at(cameraId) <<endl;
    } catch (const std::out_of_range& oor) {
        std::cerr << "\nOut of range error:" << oor.what()<< endl;
    }
    cout << "try done"<< endl;
    return 0;
}

 

运行结果:

技术图片

 

2.std::map::at错误使用

#include <iostream>
#include <string>
#include <map>
using namespace std;

std::map<int, int> g_mapIsDestroyedRefCount;

int main()
{
    int cameraId = 2;
   
   cout<< "Let‘s try"<< endl;
  g_mapIsDestroyedRefCount.insert(std::pair<int, int>(0, 2));
  cout<< "cameraId:"<< cameraId<< "count:";
 
  //介绍中说的方法一,可以访问
  cout<< g_mapIsDestroyedRefCount[cameraId]<< endl;
//方法二,异常
cameraId = 2; count
<< g_mapIsDestroyedRefCount.at(cameraId)<< endl;
cout<< "try done"<< endl;
}

运行结果:(程序异常退出)

技术图片

 

 

 

 

std::out_of_range异常

标签:container   cout   camera   string   方式   cat   inf   spl   error:   

原文地址:https://www.cnblogs.com/yemaomao/p/12358166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!