[英]Error when using EXIT_FAILURE C++
我編寫了一個簡單的代碼,將兩個向量相減,當我想在“ if條件”中返回“ EXIT_FAILURE”時,出現了一個錯誤,提示“無法將'1'從int轉換為std :: vector”。 在我的代碼中,我包括定義了EXIT_FAILURE的“ cstdlib.h”,這是我的代碼(由IDE eclipse開發)。
std::vector<double> substract_two_vectors(std::vector<double> const
&vect1,std::vector<double> const &vect2)
{
//the second vector is substracted from the first one
int size_vect1 = vect1.size();
int size_vect2 = vect2.size();
if(size_vect1!=size_vect2)
{
printf("Error, The vectors to substract should have the size size \n");
return EXIT_FAILURE;
}
//declare the vector to be filled and returned afterwards
std::vector<double> result(size_vect1);
for(int i=0;i<size_vect1;i++)
{
result[i]=vect1[i]-vect2[i];
}
return result;
}
我不知道為什么會有這個錯誤,因為我有一個C代碼執行了完全相同的操作,而我沒有這個錯誤。
在此先感謝您的幫助。
-J
您的函數的類型為std::vector<double>
並且您正在嘗試返回類型為int
的EXIT_FAILURE宏。 將該函數修改為int
類型,拋出異常或返回空向量:
return std::vector<double>{};
我相信你想要的是
std::exit(EXIT_FAILURE);
@Ron正確告訴了問題所在。
現在,讓我介紹或多或少的C ++解決方案。
std::vector<double> substract_two_vectors(std::vector<double> const &lhs,
std::vector<double> const &rhs)
{
if (lhs.size() != rhs.size())
{
throw std::invalid_argument{"vectors must be of equal sizes"};
}
std::vector<double> result(lhs.size());
std::transform(lhs.begin(), lhs.end(), rhs.begin(), result.begin(),
[](double lhs, double rhs) {return lhs - rhs;});
}
更高層次的思考,否則使用C ++毫無意義。 高效的抽象是C和C ++之間的簽名差異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.