作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是一名初学者程序员,并且正在尝试编写一个程序,询问用户以下内容:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int Count {1};
char selection {};
int Numbers {};
double Sum {0};
double Average {};
int Minimum {};
int Maximum {};
vector <int> list;
do {
cout << "P - Print Numbers" << endl;
cout << "A - Add Numbers" << endl;
cout << "M - Display The Mean Of The Numbers" << endl;
cout << "S - Display The Smallest Number" << endl;
cout << "L - Display The Largest Number" << endl;
cout << "Q - Quit" << endl;
cout << "\nEnter Your Choice: ";
cin >> selection;
switch(selection){
case 'P':
case 'p':
if(list.size() == 0){
cout << "\n[] - The List Is Empty" << endl;
} else{
cout << "\n[ ";
for(size_t i{0}; i<=list.size(); ++i)
cout << list.at(i) << " ";
cout << "]" << endl;
}
break;
case 'a':
case 'A':
cout << "\nEnter Your Number: ";
cin >> Numbers;
if (Count == 1){
Maximum = Numbers;
Minimum = Numbers;
}
if (Numbers > Maximum)
Maximum = Numbers;
if (Numbers < Minimum)
Minimum = Numbers;
list.push_back(Numbers);
cout << "Added " << Numbers << endl;
Count += 1;
break;
case 'm':
case 'M':
if (list.size() == 0)
cout << "Unable To Calculate The Mean - No Data" << endl;
else {
for (size_t j{0}; j<=list.size(); ++j){
Sum += list.at(j);
Average = Sum / list.size();
}
cout << "\nThe Mean Is : " << Average << endl;
}
break;
case 's':
case 'S':
if (list.size() == 0)
cout << "Unable To Determine The Smallest Number - List Is Empty" << endl;
else
cout << "\nThe smallest number is : " << Minimum << endl;
break;
case 'l':
case 'L':
if (list.size() == 0)
cout << "Unable To Determine The Largest Number - List Is Empty" << endl;
else
cout << "\nThe Largest number is : " << Maximum << endl;
break;
case 'q':
case 'Q':
cout << "Goodbye!!" << endl;
break;
default:
cout << "Unknown Selection, Please Try Again!" << endl;
}
} while (selection != 'q' && selection != 'Q');
return 0;
}
terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 1) >= this->size() (which is 1)
size_t
更改为
int
,但是我收到了两个警告...并且我也使用
.push_back()
作为 vector ,因此我没有空 vector ...
最佳答案
for (size_t j{0}; j<=list.size(); ++j)
中的小于或等于比较不正确。
考虑最后一次迭代... j
将等于list.size()
。
相反,对列表元素的规范迭代是:
for (size_t i{0}; i < list.size(); ++i)
std::cout << list[i] << " ";
list.at(i)
更改为
list[i]
,因为您知道索引将是有效的。
list
,因为这是C++标准库中的链接列表类型的名称。
关于c++ - 使用vector时出错:what():vector::_ M_range_check,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60006936/
我是一名初学者程序员,并且正在尝试编写一个程序,询问用户以下内容: P-打印数字 A-添加数字 M-显示数字的平均值 S-显示最小数字 L-显示最大数字 Q-退出 用户必须键入这些字母(无论是小写还是
我是一名优秀的程序员,十分优秀!