向量下标无法添加元素

The*_*Cat 2 c++ vector cin subscript

在使用子脚本操作符编写一些非常简洁的C++之后,我在程序中出现了一个小错误 - 没有输出.

我输入这个(Linux)

54 73 89 43 38 90
Run Code Online (Sandbox Code Playgroud)

然后点击Cntrl + D进行EOF.程序不输出任何内容并停止执行.

资源:

#include <iostream>
#include <string>
#include <vector>

using std::cin;
using std::vector;
using std::cout;
using std::endl;

int main() {
vector<unsigned> scores(11, 0); //11 buckets, all initially 0
unsigned grade;
while(cin >> grade) //read the grades
{
   if(grade <=100) //handles only valid inputs
  {
   ++scores[grade/10]; //increment counter for the current cluster
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

我没有在VIM中更改我的设置,因此编码风格略有偏差.我无法想象有什么问题,while循环非常标准.它会读入成绩,直到找到流无效为止.然后我检查输入是否小于100(含).最后一段代码(它非常简洁)在向量中找到正确的元素来递增计数器.

我有一种感觉,它可能是我的输入导致程序无法输出.

编辑1:我添加了输出语句,我通过使用dereferencing a来做到这一点,它始终是一个引用.

#include <iostream>
#include <string>
#include <vector>

using std::cin;
using std::vector;
using std::cout;
using std::endl;

int main() {
vector<unsigned> scores(11, 0); //11 buckets, all initially 0
unsigned grade;
while(cin >> grade) //read the grades
{
   if(grade <=100) //handles only valid inputs
  {
   ++scores[grade/10]; //increment counter for the current cluster
  }
 }
for(auto it = scores.begin(); it != scores.end(); ++it) {
cout << *it << endl;
 }
}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 6

我有一种感觉,它可能是我的输入导致程序无法输出.

不完全的.这是程序中没有输出语句导致它不输出.

  • +1我无法相信你得到了回答基本上说"你忘了写程序"的答案:-) (2认同)