停止代码而不是用错误消息中断
Stop Code instead of break with a Error Message
这是一些代码,来自一个伟大的网站,它做什么我想要的相当好(在类对象的一个向量搜索寻址类对象)。
#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
using namespacestd;
class class1
{
private:
int id;
double value;
public:
class1(int i, double v) :id(i), value(v){ }
int getId()const { return id; }
double getValue() const { return value; }
};
class HasIdentifier :public unary_function<class1, bool>
{
public:
HasIdentifier(int id) : m_id(id) { }
bool operator()(const class1& c)const
{
return (c.getId() == m_id);
}
private:
int m_id;
};
class class2
{
private:
vector <class1> objects;
public:
class2()
{
objects.push_back(class1(1, 100.0));
objects.push_back(class1(2, 100.0));
objects.push_back(class1(3, 100.0));
}
double GetValueOfId(int id)
{
vector<class1>::iterator itElem = find_if(objects.begin(), objects.end(), HasIdentifier(id));
return itElem->getValue();
}
};
int main() {
class2 c;
int id = 4;
cout << id << " " << c.GetValueOfId(id);
cin.get();
return 0;
}
它工作得很好,但每当我输入"int id ">3时,它就崩溃了,因为对象的大小只有3。我得到了这个,但是是否有可能得到警告,当这种情况发生时,它不会崩溃,但我能够在代码中以某种方式纠正它与警告消息?
您应该检查返回的迭代器是否有效,如果无效则抛出异常(或以任何其他方式报告错误):
if (itElem == objects.end())
throw MyVeryCoolException("Woops wrong id");
不要忘记设置一个全局异常处理程序(顶层捕获),否则如果异常未被捕获,应用程序仍然会崩溃。
相关文章:
- C++错误消息*成员参考.**初学者*
- 如何通过参数抛出错误消息
- glad 导致 glfwSwapBuffers 返回错误消息
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 重新定义预定义的 errno 错误消息 (E2BIG)
- SDL 映像:无法打开映像,仅显示错误消息
- 错误消息:使用"string* +="后"no match for 'operator+='"
- 错误消息"expected expression"....有人知道它为什么这么说吗?
- 在 Eclipse: "error: no match for 'operator='" 中获取错误消息
- GCC 警告和 gcc 错误消息之间的区别
- 为 c++ cin 上的输入数无效生成错误消息
- 来自带有mbedtls TLS的Mongoose Web服务器的错误消息
- 如何使用realsense摄像头调试ROS错误消息
- C++ 概念 - 需要括号中的概念会导致 2 条冲突的错误消息
- 编译器收到错误消息(textc.exe已停止)
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 使用 c++/WinRT Direct3D UWP Game DR 模板 Direct X11 的错误消息
- max_element() 给出非常奇怪的错误消息
- 不断收到错误消息,并非所有控制路径都返回值