C ++错误:无效类型'<未解决的重载=“” function =“” type =“”> [int]'

时间:2018-10-01 11:09:54

标签: c++ error-handling

因此,我完全重写了上一篇文章的代码,而Im这次尝试使用向量来完成工作。但是,在使用方括号时出现错误,将其更改为普通方括号或括号'('')'时,我的第一行会执行,但是在编写列表时会出现错误

抛出'std :: out_of_range'实例后调用

terminate   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;
}

2 个答案:

答案 0 :(得分:2)

您不能混合使用大括号,也可以使用std::vector::at

userInput.at(j)    // ok

std::vector::operator[]

userInput[j]       // ok

但不能同时

userInput.at[j]    // wrong

答案 1 :(得分:1)

这里有两个问题:

  1. 一种是对[]使用数组下标at。你必须改变它 到()
  2. 在代码的以下语句中,您最终访问了超出范围的内存,因为当juserInput.size()升至i 是0。这就是导致异常的原因。

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
相关问题