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

Vector subscription out of range, how do I eliminate this error?

本文关键字:何消 错误 范围      更新时间:2023-10-16

这是代码:

  #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;

      }

  }

当我运行程序时,我键入一个名称后跟一个分数,它说:"调试断言失败:矢量订阅超出范围"。为什么?我该如何消除此错误?

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

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