我想在我的代碼中拋出一個異常,如果從用戶輸入創建的矢量未按降序或升序排序。C++異常沒有按預期方式處理
using namespace std;
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
vector <int> vec;
//Let user fill a vector with 12 integers.
//cout << "Please note that input data should be either increasing or decreasing." << endl;
int n = 0;
int size = 0;
while(size < 12) {
cout << "Type integer to add to the vector." << endl;
cin >> n;
vec.push_back(n);
++size;
}
//throw exception if unsorted
try {
if (!((is_sorted(vec.begin(), vec.end())) || (is_sorted(vec.end(), vec.begin())))) {
throw "Input was not sorted.";
}
}
catch(exception &error){
cerr << "Error: " << error.what() << endl;
}
}
我還沒有包括代碼,該代碼搜索一個特定號碼的休息,因爲我敢肯定,這是無關緊要的這個問題。當填充到向量中的數據是升序或降序時,一切都很好,但是當我測試異常時,我得到「在調用'char const *'Aborted」的實例後終止調用,而不是我想要的錯誤消息。我不明白這裏發生了什麼事。我處理異常的方式有問題嗎?或者我不正確地使用sort()函數?
如果你交換'begin()'和'end()',你沒有得到一個向後的間隔,你會得到一個空的間隔。你想用'rbegin()'和'rend()'代替。 –
在同一個塊中拋出並捕獲異常是沒有意義的。你應該用一個簡單的'if'來代替。 – Mattia72
哇,這麼多括號!您可以將呼叫周圍的電話刪除到「is_sorted」 - 它們是多餘的。通過應用德摩根定理,你可以擺脫'if'語句中最外面的表達式:'!(A || B)'相當於'!A &&!B'。 –