![](/img/trans.png)
[英]Invalid types ‘<unresolved overloaded function type>[int]’ for array subscript - C++
[英]C++ error: invalid types '<unresolved overloaded function type>[int]'
因此,我完全重寫了上一篇文章中的代碼,而我這次試圖使用向量來完成工作。 但是,在使用方括號時出現錯誤,將其更改為普通方括號或括號'('')'時,我的第一行會執行,但是在編寫列表時會出現錯誤
拋出'std :: out_of_range'實例之后的終止調用what():vector :: _ M_range_check:__n(4)> = this-> size()(4)
編輯:我正在嘗試編寫一個代碼,該代碼接受一個輸入的元素數量,跟隨元素本身,進行冒泡排序,並進行錯誤處理。
#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::vector::at
userInput.at(j) // ok
userInput[j] // ok
但不是兩個
userInput.at[j] // wrong
這里有兩個問題:
[]
用於at
。 您必須將其更改為()
。 i
為0時j
userInput.size()
。這就是導致異常的原因。 if(userInput.at[j] > userInput.at [j + 1])
userInput.at[j] = userInput.at[j+1];
userInput.at[j+1] = temp;
解決方案是將內部for
循環更改為:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.