矢量订阅超出范围,如何消除此错误?

时间:2018-03-13 19:47:14

标签: c++ visual-studio debugging vector

代码:

  #include "stdafx.h"
  #include <iostream>
  #include <string>
  #include <vector>
  #include <algorithm>
  #include <cmath>
  using namespace std;
  inline void keep_window_open() { char ch; cin >> ch; }


  int main()
  {
      string name = "lol";
      int score = 0;
      vector<string>names;
      vector<int>scores;
      bool choose = true;
      for (int l = 0; name != "stop"; ++l) {
          cin >> name >> score;
          if (name == names[l]) choose = false;
          if (choose == true) {
              names.push_back(name);
              scores.push_back(score);
          }
          else cout << "error, name already used" << endl;
          choose = true;


      }


  }

当我运行程序时,我键入一个名称后跟一个分数,它说:&#34; debug assertion failed:vector subscription out of range&#34;。 为什么?如何消除此错误?

1 个答案:

答案 0 :(得分:0)

您尝试获取不存在的元素。首先,你需要推送一些东西

  vector<string> names;

或检查姓名是否为空:

if (!names.empty())
    if(name == names[l])
        choose = false;

还要查看你想要达到的目标,看起来你的代码总是错误,你只看你添加的姓氏。所以为了帮助你,这个解决方案可以更好地工作:

int main()
{
    string name;
    vector<string> names;

    while (cin >> name && name != "stop")
    {
        bool choose = true;

        for (auto i : names)
        {
            if (name == i)
                choose = false;
        }
        if (choose)
        {
            names.push_back(name);
        }
        else cout << "error, name already used" << endl;
    }
}