C++向量类抛出异常
C++ vector class throwing exceptions
我创建了一个包含4个字符串的向量,现在我想从第一个到最后一个读取每个字符串,并将字符串存储在exr中。我使用的是这段代码,但一旦j变为3,它就会抛出异常,因此不会提取最后一个值,也不会捕获异常。cc是一个字符串向量。我使用了调试器,字符串在向量中。有了这段代码,我只需要处理每个字符串,直到没有其他字符串为止。这就是为什么当我捕捉到使用break跳出for循环的异常时,索引比向量中的实际元素大。
std::vector<string> cc;
std::vector<string>::iterator it;
it = cc.end();
// code that stores 4 strings in cc....
....
string exr;
for (int j = 0; j < index; j++)
{
try
{
exr = cc.at(j);
}
catch (out_of_range d)
{
break;
}
//other code that use exr...
}
我预计向量没有您预期的那么大。使用向量的size()
方法,而不是对照index
检查范围。例如:
for (size_t j = 0; j < cc.size(); ++j)
您有以下代码:
对于(int j=0;j<index;j++)
但是index
的值是多少?它等于矢量大小吗?
您可能希望在for循环中使用std::vector::size()
:
for (size_t j = 0; j < cc.size(); ++j)
或者,您可以只使用基于范围的for循环(从C++11开始可用):
// Use const auto& for observing the strings in the vector:
for (const auto& exr : cc)
还要注意的是,引用应该捕获异常,以避免深度复制:
// Your code:
// catch (out_of_range d)
//
// Better:
catch(const out_of_range& d)
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- 函数如何通知用户它基于函数原型抛出异常?
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- VisualStudios 会抛出异常,而代码块不会 [C++]
- 如果不包含 pthread,为什么 GCC 的线程标准库实现会抛出异常?
- ZMQ::send() 抛出异常并终止 QNX 进程.为什么以及如何从中恢复?
- new(std::nothrow) int[n] 抛出异常
- 为什么g_object_set抛出异常(vcruntime140.dll)?
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- C++子线程抛出异常
- 我们应该在抛出异常之前取消分配内存吗
- 有没有一种方法可以让OpenCLC++绑定为所有错误抛出异常
- 为什么访问模板化变体作为返回值抛出异常
- 如何实现,错误分配中止而不是抛出异常
- std::p riority_queue::p op什么时候会抛出异常
- 在0x5914F3BE抛出异常(基于.dll)
- std::vector 默认构造函数可以抛出异常吗?
- 挂钩创建文件抛出异常:读取访问冲突
- 模板类映射构建在stl :: structs的向量上 - 寻找无效的键(stl :: string)并抛出异常
- C++向量类抛出异常