std::out_of_range字符串比较中的异常
std::out_of_range exception in string compare
我正在尝试使用std::string的比较功能。这是我的代码:
int main() {
string str1 = {"apple"};
vector<string> vec1 = {"apple"};
string suffix = {"le"};
if (str1.compare(str1.size() - suffix.length(), suffix.length(), suffix) == 0)
cout << "Yes!!" << endl; // This prints
if (vec1[0].compare(vec1[0][vec1[0].size() - suffix.length()], suffix.length(), suffix) == 0)
cout << "Yes-1!!" << endl; // This doesn't
}
输出为:
Yes!!
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::compare: __pos (which is 108) > this->size() (which
is 5)
Aborted (core dumped)
需要一些帮助来弄清楚我做错了什么。谢谢。
我已将您的第二个调用更改为compare()
:
if (vec1[0].compare(vec1[0].size() - suffix.length(), suffix.length(), suffix) == 0)
因为不清楚我们在最初的通话中试图完成什么。
这是无需抛出错误即可工作的完整代码:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main() {
string str1 = {"apple"};
vector<string> vec1 = {"apple"};
string suffix = {"le"};
if (str1.compare(str1.size() - suffix.length(), suffix.length(), suffix) == 0)
cout << "Yes!!" << endl; // This prints
if (vec1[0].compare(vec1[0].size() - suffix.length(), suffix.length(), suffix) == 0)
cout << "Yes-1!!" << endl; // This doesn't
}
另外,请注意代码中带有拼写错误的帖子,因为对该问题的评论已经指出。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 处理多个异常集合的C++方法
- 为什么比较运算符如此快速
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- std::out_of_range字符串比较中的异常
- 基于对象的两个属性的自定义比较器会引发异常
- 如何将std :: System_error异常与std :: errc值进行比较.据我了解,
- 启用优化时的堆栈指针比较异常
- 使用std::sort比较器函数时出现异常错误
- std::list<myclass*>::迭代器比较的异常行为
- 比较 (int)double 和 (int)int 时出现异常
- 比较 (int)double 和 (int)int 时出现异常