C++ C++;错误:无效类型'&书信电报;未解析的重载函数类型>;[int]';
所以我完全重写了前面的代码,这次我尝试使用向量来完成这项工作。然而,在使用方括号时,我得到了一个错误,当将它们更改为普通括号或括号“(“”)”时,我的第一行执行,但在编写列表时,它给出了一个错误 在抛出'std::out_of_range'的实例后调用terminate what():vector::_M_range_check:__n(4)>=this->size()(4)C++ C++;错误:无效类型'&书信电报;未解析的重载函数类型>;[int]';,c++,error-handling,C++,Error Handling,所以我完全重写了前面的代码,这次我尝试使用向量来完成这项工作。然而,在使用方括号时,我得到了一个错误,当将它们更改为普通括号或括号“(“”)”时,我的第一行执行,但在编写列表时,它给出了一个错误 在抛出'std::out_of_range'的实例后调用terminate what():vector::_M_range_check:__n(4)>=this->size()(4) 编辑:我试图编写一个代码,在元素本身之后,输入元素的数量,进行冒泡排序,并进行错误处理 #include<iost
编辑:我试图编写一个代码,在元素本身之后,输入元素的数量,进行冒泡排序,并进行错误处理
#include<iostream>
#include<cctype>
#include<stdexcept>
#include<vector>
using namespace std;
int main()
{
int i,j,temp,numElements;
cout << "Please enter the number of elements:";
try
{
cin >> numElements;
vector<int> userInput(numElements);
cout << endl;
cout << "Enter the list to be sorted:";
cout << endl;
for(i = 0;i < userInput.size(); ++i)
{
cin >> userInput.at(i);
if (cin.fail())
{
throw runtime_error("invalid input");
}
}
for(i = 0;i < userInput.size(); ++i)
{
for(j = 0;j < (userInput.size() - i); ++j)
if(userInput.at[j] > userInput.at [j + 1])
{
temp = userInput.at[j];
userInput.at[j] = userInput.at[j+1];
userInput.at[j+1] = temp;
}
}
cout<<"The sorted list is:";
for(i = 0; i < userInput.size(); ++i)
cout<<" "<< userInput[i];
}
catch (runtime_error& excpt)
{
cout << "error: " << excpt.what() << endl;
}
return 0;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
内部i、j、温度、数值;
组件;
向量用户输入(numElements);
cout userInput.at[j+1])
{
temp=用户输入。在[j]处;
userInput.at[j]=userInput.at[j+1];
在[j+1]处的用户输入=温度;
}
}
cout你不能混合搭配大括号,你可以使用
或
但不是两者都有
userInput.at[j] // wrong
这里有两个问题:
一种是使用数组下标[]
表示at
。你必须改变它
到()
李>
在下面代码中的语句中,您最终访问了一个越界内存,因为j
在i
是0。这就是导致异常的原因
if(userInput.at[j]>userInput.at[j+1])
userInput.at[j]=userInput.at[j+1]代码>
userInput.at[j+1]=temp代码>
解决方法是将
的内部循环更改为:
for(j = 0;j < (userInput.size() - i - 1); ++j)
那么这里的问题是什么?这是家庭作业吗?在我看来,你所需要做的就是读取抛出的异常意味着什么。我正在尝试编写一个代码,根据元素本身,根据输入的元素数进行冒泡排序。
userInput.at[j] // wrong
for(j = 0;j < (userInput.size() - i - 1); ++j)
Please enter the number of elements:4
Enter the list to be sorted:
98 78 56 23
The sorted list is: 23 56 78 98